PackageManagerService.java revision 095d4125be2117d1bbcdc815dffe6ecc0b7e651f
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    final boolean mIsPreNMR1Upgrade;
537
538    /** The location for ASEC container files on internal storage. */
539    final String mAsecInternalPath;
540
541    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
542    // LOCK HELD.  Can be called with mInstallLock held.
543    @GuardedBy("mInstallLock")
544    final Installer mInstaller;
545
546    /** Directory where installed third-party apps stored */
547    final File mAppInstallDir;
548    final File mEphemeralInstallDir;
549
550    /**
551     * Directory to which applications installed internally have their
552     * 32 bit native libraries copied.
553     */
554    private File mAppLib32InstallDir;
555
556    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
557    // apps.
558    final File mDrmAppPrivateInstallDir;
559
560    // ----------------------------------------------------------------
561
562    // Lock for state used when installing and doing other long running
563    // operations.  Methods that must be called with this lock held have
564    // the suffix "LI".
565    final Object mInstallLock = new Object();
566
567    // ----------------------------------------------------------------
568
569    // Keys are String (package name), values are Package.  This also serves
570    // as the lock for the global state.  Methods that must be called with
571    // this lock held have the prefix "LP".
572    @GuardedBy("mPackages")
573    final ArrayMap<String, PackageParser.Package> mPackages =
574            new ArrayMap<String, PackageParser.Package>();
575
576    final ArrayMap<String, Set<String>> mKnownCodebase =
577            new ArrayMap<String, Set<String>>();
578
579    // Tracks available target package names -> overlay package paths.
580    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
581        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
582
583    /**
584     * Tracks new system packages [received in an OTA] that we expect to
585     * find updated user-installed versions. Keys are package name, values
586     * are package location.
587     */
588    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
589    /**
590     * Tracks high priority intent filters for protected actions. During boot, certain
591     * filter actions are protected and should never be allowed to have a high priority
592     * intent filter for them. However, there is one, and only one exception -- the
593     * setup wizard. It must be able to define a high priority intent filter for these
594     * actions to ensure there are no escapes from the wizard. We need to delay processing
595     * of these during boot as we need to look at all of the system packages in order
596     * to know which component is the setup wizard.
597     */
598    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
599    /**
600     * Whether or not processing protected filters should be deferred.
601     */
602    private boolean mDeferProtectedFilters = true;
603
604    /**
605     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
606     */
607    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
608    /**
609     * Whether or not system app permissions should be promoted from install to runtime.
610     */
611    boolean mPromoteSystemApps;
612
613    @GuardedBy("mPackages")
614    final Settings mSettings;
615
616    /**
617     * Set of package names that are currently "frozen", which means active
618     * surgery is being done on the code/data for that package. The platform
619     * will refuse to launch frozen packages to avoid race conditions.
620     *
621     * @see PackageFreezer
622     */
623    @GuardedBy("mPackages")
624    final ArraySet<String> mFrozenPackages = new ArraySet<>();
625
626    final ProtectedPackages mProtectedPackages;
627
628    boolean mFirstBoot;
629
630    // System configuration read by SystemConfig.
631    final int[] mGlobalGids;
632    final SparseArray<ArraySet<String>> mSystemPermissions;
633    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
634
635    // If mac_permissions.xml was found for seinfo labeling.
636    boolean mFoundPolicyFile;
637
638    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
639
640    public static final class SharedLibraryEntry {
641        public final String path;
642        public final String apk;
643
644        SharedLibraryEntry(String _path, String _apk) {
645            path = _path;
646            apk = _apk;
647        }
648    }
649
650    // Currently known shared libraries.
651    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
652            new ArrayMap<String, SharedLibraryEntry>();
653
654    // All available activities, for your resolving pleasure.
655    final ActivityIntentResolver mActivities =
656            new ActivityIntentResolver();
657
658    // All available receivers, for your resolving pleasure.
659    final ActivityIntentResolver mReceivers =
660            new ActivityIntentResolver();
661
662    // All available services, for your resolving pleasure.
663    final ServiceIntentResolver mServices = new ServiceIntentResolver();
664
665    // All available providers, for your resolving pleasure.
666    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
667
668    // Mapping from provider base names (first directory in content URI codePath)
669    // to the provider information.
670    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
671            new ArrayMap<String, PackageParser.Provider>();
672
673    // Mapping from instrumentation class names to info about them.
674    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
675            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
676
677    // Mapping from permission names to info about them.
678    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
679            new ArrayMap<String, PackageParser.PermissionGroup>();
680
681    // Packages whose data we have transfered into another package, thus
682    // should no longer exist.
683    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
684
685    // Broadcast actions that are only available to the system.
686    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
687
688    /** List of packages waiting for verification. */
689    final SparseArray<PackageVerificationState> mPendingVerification
690            = new SparseArray<PackageVerificationState>();
691
692    /** Set of packages associated with each app op permission. */
693    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
694
695    final PackageInstallerService mInstallerService;
696
697    private final PackageDexOptimizer mPackageDexOptimizer;
698
699    private AtomicInteger mNextMoveId = new AtomicInteger();
700    private final MoveCallbacks mMoveCallbacks;
701
702    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
703
704    // Cache of users who need badging.
705    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
706
707    /** Token for keys in mPendingVerification. */
708    private int mPendingVerificationToken = 0;
709
710    volatile boolean mSystemReady;
711    volatile boolean mSafeMode;
712    volatile boolean mHasSystemUidErrors;
713
714    ApplicationInfo mAndroidApplication;
715    final ActivityInfo mResolveActivity = new ActivityInfo();
716    final ResolveInfo mResolveInfo = new ResolveInfo();
717    ComponentName mResolveComponentName;
718    PackageParser.Package mPlatformPackage;
719    ComponentName mCustomResolverComponentName;
720
721    boolean mResolverReplaced = false;
722
723    private final @Nullable ComponentName mIntentFilterVerifierComponent;
724    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
725
726    private int mIntentFilterVerificationToken = 0;
727
728    /** Component that knows whether or not an ephemeral application exists */
729    final ComponentName mEphemeralResolverComponent;
730    /** The service connection to the ephemeral resolver */
731    final EphemeralResolverConnection mEphemeralResolverConnection;
732
733    /** Component used to install ephemeral applications */
734    final ComponentName mEphemeralInstallerComponent;
735    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
736    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
737
738    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
739            = new SparseArray<IntentFilterVerificationState>();
740
741    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
742            new DefaultPermissionGrantPolicy(this);
743
744    // List of packages names to keep cached, even if they are uninstalled for all users
745    private List<String> mKeepUninstalledPackages;
746
747    private UserManagerInternal mUserManagerInternal;
748
749    private static class IFVerificationParams {
750        PackageParser.Package pkg;
751        boolean replacing;
752        int userId;
753        int verifierUid;
754
755        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
756                int _userId, int _verifierUid) {
757            pkg = _pkg;
758            replacing = _replacing;
759            userId = _userId;
760            replacing = _replacing;
761            verifierUid = _verifierUid;
762        }
763    }
764
765    private interface IntentFilterVerifier<T extends IntentFilter> {
766        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
767                                               T filter, String packageName);
768        void startVerifications(int userId);
769        void receiveVerificationResponse(int verificationId);
770    }
771
772    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
773        private Context mContext;
774        private ComponentName mIntentFilterVerifierComponent;
775        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
776
777        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
778            mContext = context;
779            mIntentFilterVerifierComponent = verifierComponent;
780        }
781
782        private String getDefaultScheme() {
783            return IntentFilter.SCHEME_HTTPS;
784        }
785
786        @Override
787        public void startVerifications(int userId) {
788            // Launch verifications requests
789            int count = mCurrentIntentFilterVerifications.size();
790            for (int n=0; n<count; n++) {
791                int verificationId = mCurrentIntentFilterVerifications.get(n);
792                final IntentFilterVerificationState ivs =
793                        mIntentFilterVerificationStates.get(verificationId);
794
795                String packageName = ivs.getPackageName();
796
797                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
798                final int filterCount = filters.size();
799                ArraySet<String> domainsSet = new ArraySet<>();
800                for (int m=0; m<filterCount; m++) {
801                    PackageParser.ActivityIntentInfo filter = filters.get(m);
802                    domainsSet.addAll(filter.getHostsList());
803                }
804                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
805                synchronized (mPackages) {
806                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
807                            packageName, domainsList) != null) {
808                        scheduleWriteSettingsLocked();
809                    }
810                }
811                sendVerificationRequest(userId, verificationId, ivs);
812            }
813            mCurrentIntentFilterVerifications.clear();
814        }
815
816        private void sendVerificationRequest(int userId, int verificationId,
817                IntentFilterVerificationState ivs) {
818
819            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
820            verificationIntent.putExtra(
821                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
822                    verificationId);
823            verificationIntent.putExtra(
824                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
825                    getDefaultScheme());
826            verificationIntent.putExtra(
827                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
828                    ivs.getHostsString());
829            verificationIntent.putExtra(
830                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
831                    ivs.getPackageName());
832            verificationIntent.setComponent(mIntentFilterVerifierComponent);
833            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
834
835            UserHandle user = new UserHandle(userId);
836            mContext.sendBroadcastAsUser(verificationIntent, user);
837            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
838                    "Sending IntentFilter verification broadcast");
839        }
840
841        public void receiveVerificationResponse(int verificationId) {
842            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
843
844            final boolean verified = ivs.isVerified();
845
846            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
847            final int count = filters.size();
848            if (DEBUG_DOMAIN_VERIFICATION) {
849                Slog.i(TAG, "Received verification response " + verificationId
850                        + " for " + count + " filters, verified=" + verified);
851            }
852            for (int n=0; n<count; n++) {
853                PackageParser.ActivityIntentInfo filter = filters.get(n);
854                filter.setVerified(verified);
855
856                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
857                        + " verified with result:" + verified + " and hosts:"
858                        + ivs.getHostsString());
859            }
860
861            mIntentFilterVerificationStates.remove(verificationId);
862
863            final String packageName = ivs.getPackageName();
864            IntentFilterVerificationInfo ivi = null;
865
866            synchronized (mPackages) {
867                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
868            }
869            if (ivi == null) {
870                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
871                        + verificationId + " packageName:" + packageName);
872                return;
873            }
874            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
875                    "Updating IntentFilterVerificationInfo for package " + packageName
876                            +" verificationId:" + verificationId);
877
878            synchronized (mPackages) {
879                if (verified) {
880                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
881                } else {
882                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
883                }
884                scheduleWriteSettingsLocked();
885
886                final int userId = ivs.getUserId();
887                if (userId != UserHandle.USER_ALL) {
888                    final int userStatus =
889                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
890
891                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
892                    boolean needUpdate = false;
893
894                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
895                    // already been set by the User thru the Disambiguation dialog
896                    switch (userStatus) {
897                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
898                            if (verified) {
899                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
900                            } else {
901                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
902                            }
903                            needUpdate = true;
904                            break;
905
906                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
907                            if (verified) {
908                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
909                                needUpdate = true;
910                            }
911                            break;
912
913                        default:
914                            // Nothing to do
915                    }
916
917                    if (needUpdate) {
918                        mSettings.updateIntentFilterVerificationStatusLPw(
919                                packageName, updatedStatus, userId);
920                        scheduleWritePackageRestrictionsLocked(userId);
921                    }
922                }
923            }
924        }
925
926        @Override
927        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
928                    ActivityIntentInfo filter, String packageName) {
929            if (!hasValidDomains(filter)) {
930                return false;
931            }
932            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
933            if (ivs == null) {
934                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
935                        packageName);
936            }
937            if (DEBUG_DOMAIN_VERIFICATION) {
938                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
939            }
940            ivs.addFilter(filter);
941            return true;
942        }
943
944        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
945                int userId, int verificationId, String packageName) {
946            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
947                    verifierUid, userId, packageName);
948            ivs.setPendingState();
949            synchronized (mPackages) {
950                mIntentFilterVerificationStates.append(verificationId, ivs);
951                mCurrentIntentFilterVerifications.add(verificationId);
952            }
953            return ivs;
954        }
955    }
956
957    private static boolean hasValidDomains(ActivityIntentInfo filter) {
958        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
959                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
960                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
961    }
962
963    // Set of pending broadcasts for aggregating enable/disable of components.
964    static class PendingPackageBroadcasts {
965        // for each user id, a map of <package name -> components within that package>
966        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
967
968        public PendingPackageBroadcasts() {
969            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
970        }
971
972        public ArrayList<String> get(int userId, String packageName) {
973            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
974            return packages.get(packageName);
975        }
976
977        public void put(int userId, String packageName, ArrayList<String> components) {
978            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
979            packages.put(packageName, components);
980        }
981
982        public void remove(int userId, String packageName) {
983            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
984            if (packages != null) {
985                packages.remove(packageName);
986            }
987        }
988
989        public void remove(int userId) {
990            mUidMap.remove(userId);
991        }
992
993        public int userIdCount() {
994            return mUidMap.size();
995        }
996
997        public int userIdAt(int n) {
998            return mUidMap.keyAt(n);
999        }
1000
1001        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1002            return mUidMap.get(userId);
1003        }
1004
1005        public int size() {
1006            // total number of pending broadcast entries across all userIds
1007            int num = 0;
1008            for (int i = 0; i< mUidMap.size(); i++) {
1009                num += mUidMap.valueAt(i).size();
1010            }
1011            return num;
1012        }
1013
1014        public void clear() {
1015            mUidMap.clear();
1016        }
1017
1018        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1019            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1020            if (map == null) {
1021                map = new ArrayMap<String, ArrayList<String>>();
1022                mUidMap.put(userId, map);
1023            }
1024            return map;
1025        }
1026    }
1027    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1028
1029    // Service Connection to remote media container service to copy
1030    // package uri's from external media onto secure containers
1031    // or internal storage.
1032    private IMediaContainerService mContainerService = null;
1033
1034    static final int SEND_PENDING_BROADCAST = 1;
1035    static final int MCS_BOUND = 3;
1036    static final int END_COPY = 4;
1037    static final int INIT_COPY = 5;
1038    static final int MCS_UNBIND = 6;
1039    static final int START_CLEANING_PACKAGE = 7;
1040    static final int FIND_INSTALL_LOC = 8;
1041    static final int POST_INSTALL = 9;
1042    static final int MCS_RECONNECT = 10;
1043    static final int MCS_GIVE_UP = 11;
1044    static final int UPDATED_MEDIA_STATUS = 12;
1045    static final int WRITE_SETTINGS = 13;
1046    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1047    static final int PACKAGE_VERIFIED = 15;
1048    static final int CHECK_PENDING_VERIFICATION = 16;
1049    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1050    static final int INTENT_FILTER_VERIFIED = 18;
1051    static final int WRITE_PACKAGE_LIST = 19;
1052
1053    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1054
1055    // Delay time in millisecs
1056    static final int BROADCAST_DELAY = 10 * 1000;
1057
1058    static UserManagerService sUserManager;
1059
1060    // Stores a list of users whose package restrictions file needs to be updated
1061    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1062
1063    final private DefaultContainerConnection mDefContainerConn =
1064            new DefaultContainerConnection();
1065    class DefaultContainerConnection implements ServiceConnection {
1066        public void onServiceConnected(ComponentName name, IBinder service) {
1067            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1068            IMediaContainerService imcs =
1069                IMediaContainerService.Stub.asInterface(service);
1070            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1071        }
1072
1073        public void onServiceDisconnected(ComponentName name) {
1074            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1075        }
1076    }
1077
1078    // Recordkeeping of restore-after-install operations that are currently in flight
1079    // between the Package Manager and the Backup Manager
1080    static class PostInstallData {
1081        public InstallArgs args;
1082        public PackageInstalledInfo res;
1083
1084        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1085            args = _a;
1086            res = _r;
1087        }
1088    }
1089
1090    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1091    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1092
1093    // XML tags for backup/restore of various bits of state
1094    private static final String TAG_PREFERRED_BACKUP = "pa";
1095    private static final String TAG_DEFAULT_APPS = "da";
1096    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1097
1098    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1099    private static final String TAG_ALL_GRANTS = "rt-grants";
1100    private static final String TAG_GRANT = "grant";
1101    private static final String ATTR_PACKAGE_NAME = "pkg";
1102
1103    private static final String TAG_PERMISSION = "perm";
1104    private static final String ATTR_PERMISSION_NAME = "name";
1105    private static final String ATTR_IS_GRANTED = "g";
1106    private static final String ATTR_USER_SET = "set";
1107    private static final String ATTR_USER_FIXED = "fixed";
1108    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1109
1110    // System/policy permission grants are not backed up
1111    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1112            FLAG_PERMISSION_POLICY_FIXED
1113            | FLAG_PERMISSION_SYSTEM_FIXED
1114            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1115
1116    // And we back up these user-adjusted states
1117    private static final int USER_RUNTIME_GRANT_MASK =
1118            FLAG_PERMISSION_USER_SET
1119            | FLAG_PERMISSION_USER_FIXED
1120            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1121
1122    final @Nullable String mRequiredVerifierPackage;
1123    final @NonNull String mRequiredInstallerPackage;
1124    final @Nullable String mSetupWizardPackage;
1125    final @NonNull String mServicesSystemSharedLibraryPackageName;
1126    final @NonNull String mSharedSystemSharedLibraryPackageName;
1127
1128    private final PackageUsage mPackageUsage = new PackageUsage();
1129    private final CompilerStats mCompilerStats = new CompilerStats();
1130
1131    class PackageHandler extends Handler {
1132        private boolean mBound = false;
1133        final ArrayList<HandlerParams> mPendingInstalls =
1134            new ArrayList<HandlerParams>();
1135
1136        private boolean connectToService() {
1137            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1138                    " DefaultContainerService");
1139            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1140            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1141            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1142                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1143                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1144                mBound = true;
1145                return true;
1146            }
1147            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1148            return false;
1149        }
1150
1151        private void disconnectService() {
1152            mContainerService = null;
1153            mBound = false;
1154            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1155            mContext.unbindService(mDefContainerConn);
1156            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1157        }
1158
1159        PackageHandler(Looper looper) {
1160            super(looper);
1161        }
1162
1163        public void handleMessage(Message msg) {
1164            try {
1165                doHandleMessage(msg);
1166            } finally {
1167                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1168            }
1169        }
1170
1171        void doHandleMessage(Message msg) {
1172            switch (msg.what) {
1173                case INIT_COPY: {
1174                    HandlerParams params = (HandlerParams) msg.obj;
1175                    int idx = mPendingInstalls.size();
1176                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1177                    // If a bind was already initiated we dont really
1178                    // need to do anything. The pending install
1179                    // will be processed later on.
1180                    if (!mBound) {
1181                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1182                                System.identityHashCode(mHandler));
1183                        // If this is the only one pending we might
1184                        // have to bind to the service again.
1185                        if (!connectToService()) {
1186                            Slog.e(TAG, "Failed to bind to media container service");
1187                            params.serviceError();
1188                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1189                                    System.identityHashCode(mHandler));
1190                            if (params.traceMethod != null) {
1191                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1192                                        params.traceCookie);
1193                            }
1194                            return;
1195                        } else {
1196                            // Once we bind to the service, the first
1197                            // pending request will be processed.
1198                            mPendingInstalls.add(idx, params);
1199                        }
1200                    } else {
1201                        mPendingInstalls.add(idx, params);
1202                        // Already bound to the service. Just make
1203                        // sure we trigger off processing the first request.
1204                        if (idx == 0) {
1205                            mHandler.sendEmptyMessage(MCS_BOUND);
1206                        }
1207                    }
1208                    break;
1209                }
1210                case MCS_BOUND: {
1211                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1212                    if (msg.obj != null) {
1213                        mContainerService = (IMediaContainerService) msg.obj;
1214                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1215                                System.identityHashCode(mHandler));
1216                    }
1217                    if (mContainerService == null) {
1218                        if (!mBound) {
1219                            // Something seriously wrong since we are not bound and we are not
1220                            // waiting for connection. Bail out.
1221                            Slog.e(TAG, "Cannot bind to media container service");
1222                            for (HandlerParams params : mPendingInstalls) {
1223                                // Indicate service bind error
1224                                params.serviceError();
1225                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1226                                        System.identityHashCode(params));
1227                                if (params.traceMethod != null) {
1228                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1229                                            params.traceMethod, params.traceCookie);
1230                                }
1231                                return;
1232                            }
1233                            mPendingInstalls.clear();
1234                        } else {
1235                            Slog.w(TAG, "Waiting to connect to media container service");
1236                        }
1237                    } else if (mPendingInstalls.size() > 0) {
1238                        HandlerParams params = mPendingInstalls.get(0);
1239                        if (params != null) {
1240                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1241                                    System.identityHashCode(params));
1242                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1243                            if (params.startCopy()) {
1244                                // We are done...  look for more work or to
1245                                // go idle.
1246                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1247                                        "Checking for more work or unbind...");
1248                                // Delete pending install
1249                                if (mPendingInstalls.size() > 0) {
1250                                    mPendingInstalls.remove(0);
1251                                }
1252                                if (mPendingInstalls.size() == 0) {
1253                                    if (mBound) {
1254                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1255                                                "Posting delayed MCS_UNBIND");
1256                                        removeMessages(MCS_UNBIND);
1257                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1258                                        // Unbind after a little delay, to avoid
1259                                        // continual thrashing.
1260                                        sendMessageDelayed(ubmsg, 10000);
1261                                    }
1262                                } else {
1263                                    // There are more pending requests in queue.
1264                                    // Just post MCS_BOUND message to trigger processing
1265                                    // of next pending install.
1266                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1267                                            "Posting MCS_BOUND for next work");
1268                                    mHandler.sendEmptyMessage(MCS_BOUND);
1269                                }
1270                            }
1271                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1272                        }
1273                    } else {
1274                        // Should never happen ideally.
1275                        Slog.w(TAG, "Empty queue");
1276                    }
1277                    break;
1278                }
1279                case MCS_RECONNECT: {
1280                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1281                    if (mPendingInstalls.size() > 0) {
1282                        if (mBound) {
1283                            disconnectService();
1284                        }
1285                        if (!connectToService()) {
1286                            Slog.e(TAG, "Failed to bind to media container service");
1287                            for (HandlerParams params : mPendingInstalls) {
1288                                // Indicate service bind error
1289                                params.serviceError();
1290                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1291                                        System.identityHashCode(params));
1292                            }
1293                            mPendingInstalls.clear();
1294                        }
1295                    }
1296                    break;
1297                }
1298                case MCS_UNBIND: {
1299                    // If there is no actual work left, then time to unbind.
1300                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1301
1302                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1303                        if (mBound) {
1304                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1305
1306                            disconnectService();
1307                        }
1308                    } else if (mPendingInstalls.size() > 0) {
1309                        // There are more pending requests in queue.
1310                        // Just post MCS_BOUND message to trigger processing
1311                        // of next pending install.
1312                        mHandler.sendEmptyMessage(MCS_BOUND);
1313                    }
1314
1315                    break;
1316                }
1317                case MCS_GIVE_UP: {
1318                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1319                    HandlerParams params = mPendingInstalls.remove(0);
1320                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1321                            System.identityHashCode(params));
1322                    break;
1323                }
1324                case SEND_PENDING_BROADCAST: {
1325                    String packages[];
1326                    ArrayList<String> components[];
1327                    int size = 0;
1328                    int uids[];
1329                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1330                    synchronized (mPackages) {
1331                        if (mPendingBroadcasts == null) {
1332                            return;
1333                        }
1334                        size = mPendingBroadcasts.size();
1335                        if (size <= 0) {
1336                            // Nothing to be done. Just return
1337                            return;
1338                        }
1339                        packages = new String[size];
1340                        components = new ArrayList[size];
1341                        uids = new int[size];
1342                        int i = 0;  // filling out the above arrays
1343
1344                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1345                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1346                            Iterator<Map.Entry<String, ArrayList<String>>> it
1347                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1348                                            .entrySet().iterator();
1349                            while (it.hasNext() && i < size) {
1350                                Map.Entry<String, ArrayList<String>> ent = it.next();
1351                                packages[i] = ent.getKey();
1352                                components[i] = ent.getValue();
1353                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1354                                uids[i] = (ps != null)
1355                                        ? UserHandle.getUid(packageUserId, ps.appId)
1356                                        : -1;
1357                                i++;
1358                            }
1359                        }
1360                        size = i;
1361                        mPendingBroadcasts.clear();
1362                    }
1363                    // Send broadcasts
1364                    for (int i = 0; i < size; i++) {
1365                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1366                    }
1367                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1368                    break;
1369                }
1370                case START_CLEANING_PACKAGE: {
1371                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1372                    final String packageName = (String)msg.obj;
1373                    final int userId = msg.arg1;
1374                    final boolean andCode = msg.arg2 != 0;
1375                    synchronized (mPackages) {
1376                        if (userId == UserHandle.USER_ALL) {
1377                            int[] users = sUserManager.getUserIds();
1378                            for (int user : users) {
1379                                mSettings.addPackageToCleanLPw(
1380                                        new PackageCleanItem(user, packageName, andCode));
1381                            }
1382                        } else {
1383                            mSettings.addPackageToCleanLPw(
1384                                    new PackageCleanItem(userId, packageName, andCode));
1385                        }
1386                    }
1387                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1388                    startCleaningPackages();
1389                } break;
1390                case POST_INSTALL: {
1391                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1392
1393                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1394                    final boolean didRestore = (msg.arg2 != 0);
1395                    mRunningInstalls.delete(msg.arg1);
1396
1397                    if (data != null) {
1398                        InstallArgs args = data.args;
1399                        PackageInstalledInfo parentRes = data.res;
1400
1401                        final boolean grantPermissions = (args.installFlags
1402                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1403                        final boolean killApp = (args.installFlags
1404                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1405                        final String[] grantedPermissions = args.installGrantPermissions;
1406
1407                        // Handle the parent package
1408                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1409                                grantedPermissions, didRestore, args.installerPackageName,
1410                                args.observer);
1411
1412                        // Handle the child packages
1413                        final int childCount = (parentRes.addedChildPackages != null)
1414                                ? parentRes.addedChildPackages.size() : 0;
1415                        for (int i = 0; i < childCount; i++) {
1416                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1417                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1418                                    grantedPermissions, false, args.installerPackageName,
1419                                    args.observer);
1420                        }
1421
1422                        // Log tracing if needed
1423                        if (args.traceMethod != null) {
1424                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1425                                    args.traceCookie);
1426                        }
1427                    } else {
1428                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1429                    }
1430
1431                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1432                } break;
1433                case UPDATED_MEDIA_STATUS: {
1434                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1435                    boolean reportStatus = msg.arg1 == 1;
1436                    boolean doGc = msg.arg2 == 1;
1437                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1438                    if (doGc) {
1439                        // Force a gc to clear up stale containers.
1440                        Runtime.getRuntime().gc();
1441                    }
1442                    if (msg.obj != null) {
1443                        @SuppressWarnings("unchecked")
1444                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1445                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1446                        // Unload containers
1447                        unloadAllContainers(args);
1448                    }
1449                    if (reportStatus) {
1450                        try {
1451                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1452                            PackageHelper.getMountService().finishMediaUpdate();
1453                        } catch (RemoteException e) {
1454                            Log.e(TAG, "MountService not running?");
1455                        }
1456                    }
1457                } break;
1458                case WRITE_SETTINGS: {
1459                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1460                    synchronized (mPackages) {
1461                        removeMessages(WRITE_SETTINGS);
1462                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1463                        mSettings.writeLPr();
1464                        mDirtyUsers.clear();
1465                    }
1466                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1467                } break;
1468                case WRITE_PACKAGE_RESTRICTIONS: {
1469                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1470                    synchronized (mPackages) {
1471                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1472                        for (int userId : mDirtyUsers) {
1473                            mSettings.writePackageRestrictionsLPr(userId);
1474                        }
1475                        mDirtyUsers.clear();
1476                    }
1477                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1478                } break;
1479                case WRITE_PACKAGE_LIST: {
1480                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1481                    synchronized (mPackages) {
1482                        removeMessages(WRITE_PACKAGE_LIST);
1483                        mSettings.writePackageListLPr(msg.arg1);
1484                    }
1485                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1486                } break;
1487                case CHECK_PENDING_VERIFICATION: {
1488                    final int verificationId = msg.arg1;
1489                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1490
1491                    if ((state != null) && !state.timeoutExtended()) {
1492                        final InstallArgs args = state.getInstallArgs();
1493                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1494
1495                        Slog.i(TAG, "Verification timed out for " + originUri);
1496                        mPendingVerification.remove(verificationId);
1497
1498                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1499
1500                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1501                            Slog.i(TAG, "Continuing with installation of " + originUri);
1502                            state.setVerifierResponse(Binder.getCallingUid(),
1503                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1504                            broadcastPackageVerified(verificationId, originUri,
1505                                    PackageManager.VERIFICATION_ALLOW,
1506                                    state.getInstallArgs().getUser());
1507                            try {
1508                                ret = args.copyApk(mContainerService, true);
1509                            } catch (RemoteException e) {
1510                                Slog.e(TAG, "Could not contact the ContainerService");
1511                            }
1512                        } else {
1513                            broadcastPackageVerified(verificationId, originUri,
1514                                    PackageManager.VERIFICATION_REJECT,
1515                                    state.getInstallArgs().getUser());
1516                        }
1517
1518                        Trace.asyncTraceEnd(
1519                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1520
1521                        processPendingInstall(args, ret);
1522                        mHandler.sendEmptyMessage(MCS_UNBIND);
1523                    }
1524                    break;
1525                }
1526                case PACKAGE_VERIFIED: {
1527                    final int verificationId = msg.arg1;
1528
1529                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1530                    if (state == null) {
1531                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1532                        break;
1533                    }
1534
1535                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1536
1537                    state.setVerifierResponse(response.callerUid, response.code);
1538
1539                    if (state.isVerificationComplete()) {
1540                        mPendingVerification.remove(verificationId);
1541
1542                        final InstallArgs args = state.getInstallArgs();
1543                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1544
1545                        int ret;
1546                        if (state.isInstallAllowed()) {
1547                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1548                            broadcastPackageVerified(verificationId, originUri,
1549                                    response.code, state.getInstallArgs().getUser());
1550                            try {
1551                                ret = args.copyApk(mContainerService, true);
1552                            } catch (RemoteException e) {
1553                                Slog.e(TAG, "Could not contact the ContainerService");
1554                            }
1555                        } else {
1556                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1557                        }
1558
1559                        Trace.asyncTraceEnd(
1560                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1561
1562                        processPendingInstall(args, ret);
1563                        mHandler.sendEmptyMessage(MCS_UNBIND);
1564                    }
1565
1566                    break;
1567                }
1568                case START_INTENT_FILTER_VERIFICATIONS: {
1569                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1570                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1571                            params.replacing, params.pkg);
1572                    break;
1573                }
1574                case INTENT_FILTER_VERIFIED: {
1575                    final int verificationId = msg.arg1;
1576
1577                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1578                            verificationId);
1579                    if (state == null) {
1580                        Slog.w(TAG, "Invalid IntentFilter verification token "
1581                                + verificationId + " received");
1582                        break;
1583                    }
1584
1585                    final int userId = state.getUserId();
1586
1587                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1588                            "Processing IntentFilter verification with token:"
1589                            + verificationId + " and userId:" + userId);
1590
1591                    final IntentFilterVerificationResponse response =
1592                            (IntentFilterVerificationResponse) msg.obj;
1593
1594                    state.setVerifierResponse(response.callerUid, response.code);
1595
1596                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1597                            "IntentFilter verification with token:" + verificationId
1598                            + " and userId:" + userId
1599                            + " is settings verifier response with response code:"
1600                            + response.code);
1601
1602                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1603                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1604                                + response.getFailedDomainsString());
1605                    }
1606
1607                    if (state.isVerificationComplete()) {
1608                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1609                    } else {
1610                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1611                                "IntentFilter verification with token:" + verificationId
1612                                + " was not said to be complete");
1613                    }
1614
1615                    break;
1616                }
1617            }
1618        }
1619    }
1620
1621    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1622            boolean killApp, String[] grantedPermissions,
1623            boolean launchedForRestore, String installerPackage,
1624            IPackageInstallObserver2 installObserver) {
1625        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1626            // Send the removed broadcasts
1627            if (res.removedInfo != null) {
1628                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1629            }
1630
1631            // Now that we successfully installed the package, grant runtime
1632            // permissions if requested before broadcasting the install.
1633            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1634                    >= Build.VERSION_CODES.M) {
1635                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1636            }
1637
1638            final boolean update = res.removedInfo != null
1639                    && res.removedInfo.removedPackage != null;
1640
1641            // If this is the first time we have child packages for a disabled privileged
1642            // app that had no children, we grant requested runtime permissions to the new
1643            // children if the parent on the system image had them already granted.
1644            if (res.pkg.parentPackage != null) {
1645                synchronized (mPackages) {
1646                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1647                }
1648            }
1649
1650            synchronized (mPackages) {
1651                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1652            }
1653
1654            final String packageName = res.pkg.applicationInfo.packageName;
1655            Bundle extras = new Bundle(1);
1656            extras.putInt(Intent.EXTRA_UID, res.uid);
1657
1658            // Determine the set of users who are adding this package for
1659            // the first time vs. those who are seeing an update.
1660            int[] firstUsers = EMPTY_INT_ARRAY;
1661            int[] updateUsers = EMPTY_INT_ARRAY;
1662            if (res.origUsers == null || res.origUsers.length == 0) {
1663                firstUsers = res.newUsers;
1664            } else {
1665                for (int newUser : res.newUsers) {
1666                    boolean isNew = true;
1667                    for (int origUser : res.origUsers) {
1668                        if (origUser == newUser) {
1669                            isNew = false;
1670                            break;
1671                        }
1672                    }
1673                    if (isNew) {
1674                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1675                    } else {
1676                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1677                    }
1678                }
1679            }
1680
1681            // Send installed broadcasts if the install/update is not ephemeral
1682            if (!isEphemeral(res.pkg)) {
1683                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1684
1685                // Send added for users that see the package for the first time
1686                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1687                        extras, 0 /*flags*/, null /*targetPackage*/,
1688                        null /*finishedReceiver*/, firstUsers);
1689
1690                // Send added for users that don't see the package for the first time
1691                if (update) {
1692                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1693                }
1694                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1695                        extras, 0 /*flags*/, null /*targetPackage*/,
1696                        null /*finishedReceiver*/, updateUsers);
1697
1698                // Send replaced for users that don't see the package for the first time
1699                if (update) {
1700                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1701                            packageName, extras, 0 /*flags*/,
1702                            null /*targetPackage*/, null /*finishedReceiver*/,
1703                            updateUsers);
1704                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1705                            null /*package*/, null /*extras*/, 0 /*flags*/,
1706                            packageName /*targetPackage*/,
1707                            null /*finishedReceiver*/, updateUsers);
1708                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1709                    // First-install and we did a restore, so we're responsible for the
1710                    // first-launch broadcast.
1711                    if (DEBUG_BACKUP) {
1712                        Slog.i(TAG, "Post-restore of " + packageName
1713                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1714                    }
1715                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1716                }
1717
1718                // Send broadcast package appeared if forward locked/external for all users
1719                // treat asec-hosted packages like removable media on upgrade
1720                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1721                    if (DEBUG_INSTALL) {
1722                        Slog.i(TAG, "upgrading pkg " + res.pkg
1723                                + " is ASEC-hosted -> AVAILABLE");
1724                    }
1725                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1726                    ArrayList<String> pkgList = new ArrayList<>(1);
1727                    pkgList.add(packageName);
1728                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1729                }
1730            }
1731
1732            // Work that needs to happen on first install within each user
1733            if (firstUsers != null && firstUsers.length > 0) {
1734                synchronized (mPackages) {
1735                    for (int userId : firstUsers) {
1736                        // If this app is a browser and it's newly-installed for some
1737                        // users, clear any default-browser state in those users. The
1738                        // app's nature doesn't depend on the user, so we can just check
1739                        // its browser nature in any user and generalize.
1740                        if (packageIsBrowser(packageName, userId)) {
1741                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1742                        }
1743
1744                        // We may also need to apply pending (restored) runtime
1745                        // permission grants within these users.
1746                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1747                    }
1748                }
1749            }
1750
1751            // Log current value of "unknown sources" setting
1752            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1753                    getUnknownSourcesSettings());
1754
1755            // Force a gc to clear up things
1756            Runtime.getRuntime().gc();
1757
1758            // Remove the replaced package's older resources safely now
1759            // We delete after a gc for applications  on sdcard.
1760            if (res.removedInfo != null && res.removedInfo.args != null) {
1761                synchronized (mInstallLock) {
1762                    res.removedInfo.args.doPostDeleteLI(true);
1763                }
1764            }
1765        }
1766
1767        // If someone is watching installs - notify them
1768        if (installObserver != null) {
1769            try {
1770                Bundle extras = extrasForInstallResult(res);
1771                installObserver.onPackageInstalled(res.name, res.returnCode,
1772                        res.returnMsg, extras);
1773            } catch (RemoteException e) {
1774                Slog.i(TAG, "Observer no longer exists.");
1775            }
1776        }
1777    }
1778
1779    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1780            PackageParser.Package pkg) {
1781        if (pkg.parentPackage == null) {
1782            return;
1783        }
1784        if (pkg.requestedPermissions == null) {
1785            return;
1786        }
1787        final PackageSetting disabledSysParentPs = mSettings
1788                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1789        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1790                || !disabledSysParentPs.isPrivileged()
1791                || (disabledSysParentPs.childPackageNames != null
1792                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1793            return;
1794        }
1795        final int[] allUserIds = sUserManager.getUserIds();
1796        final int permCount = pkg.requestedPermissions.size();
1797        for (int i = 0; i < permCount; i++) {
1798            String permission = pkg.requestedPermissions.get(i);
1799            BasePermission bp = mSettings.mPermissions.get(permission);
1800            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1801                continue;
1802            }
1803            for (int userId : allUserIds) {
1804                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1805                        permission, userId)) {
1806                    grantRuntimePermission(pkg.packageName, permission, userId);
1807                }
1808            }
1809        }
1810    }
1811
1812    private StorageEventListener mStorageListener = new StorageEventListener() {
1813        @Override
1814        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1815            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1816                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1817                    final String volumeUuid = vol.getFsUuid();
1818
1819                    // Clean up any users or apps that were removed or recreated
1820                    // while this volume was missing
1821                    reconcileUsers(volumeUuid);
1822                    reconcileApps(volumeUuid);
1823
1824                    // Clean up any install sessions that expired or were
1825                    // cancelled while this volume was missing
1826                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1827
1828                    loadPrivatePackages(vol);
1829
1830                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1831                    unloadPrivatePackages(vol);
1832                }
1833            }
1834
1835            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1836                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1837                    updateExternalMediaStatus(true, false);
1838                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1839                    updateExternalMediaStatus(false, false);
1840                }
1841            }
1842        }
1843
1844        @Override
1845        public void onVolumeForgotten(String fsUuid) {
1846            if (TextUtils.isEmpty(fsUuid)) {
1847                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1848                return;
1849            }
1850
1851            // Remove any apps installed on the forgotten volume
1852            synchronized (mPackages) {
1853                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1854                for (PackageSetting ps : packages) {
1855                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1856                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1857                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1858                }
1859
1860                mSettings.onVolumeForgotten(fsUuid);
1861                mSettings.writeLPr();
1862            }
1863        }
1864    };
1865
1866    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1867            String[] grantedPermissions) {
1868        for (int userId : userIds) {
1869            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1870        }
1871
1872        // We could have touched GID membership, so flush out packages.list
1873        synchronized (mPackages) {
1874            mSettings.writePackageListLPr();
1875        }
1876    }
1877
1878    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1879            String[] grantedPermissions) {
1880        SettingBase sb = (SettingBase) pkg.mExtras;
1881        if (sb == null) {
1882            return;
1883        }
1884
1885        PermissionsState permissionsState = sb.getPermissionsState();
1886
1887        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1888                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1889
1890        for (String permission : pkg.requestedPermissions) {
1891            final BasePermission bp;
1892            synchronized (mPackages) {
1893                bp = mSettings.mPermissions.get(permission);
1894            }
1895            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1896                    && (grantedPermissions == null
1897                           || ArrayUtils.contains(grantedPermissions, permission))) {
1898                final int flags = permissionsState.getPermissionFlags(permission, userId);
1899                // Installer cannot change immutable permissions.
1900                if ((flags & immutableFlags) == 0) {
1901                    grantRuntimePermission(pkg.packageName, permission, userId);
1902                }
1903            }
1904        }
1905    }
1906
1907    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1908        Bundle extras = null;
1909        switch (res.returnCode) {
1910            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1911                extras = new Bundle();
1912                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1913                        res.origPermission);
1914                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1915                        res.origPackage);
1916                break;
1917            }
1918            case PackageManager.INSTALL_SUCCEEDED: {
1919                extras = new Bundle();
1920                extras.putBoolean(Intent.EXTRA_REPLACING,
1921                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1922                break;
1923            }
1924        }
1925        return extras;
1926    }
1927
1928    void scheduleWriteSettingsLocked() {
1929        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1930            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1931        }
1932    }
1933
1934    void scheduleWritePackageListLocked(int userId) {
1935        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1936            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1937            msg.arg1 = userId;
1938            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1939        }
1940    }
1941
1942    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1943        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1944        scheduleWritePackageRestrictionsLocked(userId);
1945    }
1946
1947    void scheduleWritePackageRestrictionsLocked(int userId) {
1948        final int[] userIds = (userId == UserHandle.USER_ALL)
1949                ? sUserManager.getUserIds() : new int[]{userId};
1950        for (int nextUserId : userIds) {
1951            if (!sUserManager.exists(nextUserId)) return;
1952            mDirtyUsers.add(nextUserId);
1953            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1954                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1955            }
1956        }
1957    }
1958
1959    public static PackageManagerService main(Context context, Installer installer,
1960            boolean factoryTest, boolean onlyCore) {
1961        // Self-check for initial settings.
1962        PackageManagerServiceCompilerMapping.checkProperties();
1963
1964        PackageManagerService m = new PackageManagerService(context, installer,
1965                factoryTest, onlyCore);
1966        m.enableSystemUserPackages();
1967        ServiceManager.addService("package", m);
1968        return m;
1969    }
1970
1971    private void enableSystemUserPackages() {
1972        if (!UserManager.isSplitSystemUser()) {
1973            return;
1974        }
1975        // For system user, enable apps based on the following conditions:
1976        // - app is whitelisted or belong to one of these groups:
1977        //   -- system app which has no launcher icons
1978        //   -- system app which has INTERACT_ACROSS_USERS permission
1979        //   -- system IME app
1980        // - app is not in the blacklist
1981        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1982        Set<String> enableApps = new ArraySet<>();
1983        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1984                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1985                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1986        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1987        enableApps.addAll(wlApps);
1988        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1989                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1990        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1991        enableApps.removeAll(blApps);
1992        Log.i(TAG, "Applications installed for system user: " + enableApps);
1993        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1994                UserHandle.SYSTEM);
1995        final int allAppsSize = allAps.size();
1996        synchronized (mPackages) {
1997            for (int i = 0; i < allAppsSize; i++) {
1998                String pName = allAps.get(i);
1999                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2000                // Should not happen, but we shouldn't be failing if it does
2001                if (pkgSetting == null) {
2002                    continue;
2003                }
2004                boolean install = enableApps.contains(pName);
2005                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2006                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2007                            + " for system user");
2008                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2009                }
2010            }
2011        }
2012    }
2013
2014    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2015        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2016                Context.DISPLAY_SERVICE);
2017        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2018    }
2019
2020    /**
2021     * Requests that files preopted on a secondary system partition be copied to the data partition
2022     * if possible.  Note that the actual copying of the files is accomplished by init for security
2023     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2024     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2025     */
2026    private static void requestCopyPreoptedFiles() {
2027        final int WAIT_TIME_MS = 100;
2028        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2029        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2030            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2031            // We will wait for up to 100 seconds.
2032            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2033            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2034                try {
2035                    Thread.sleep(WAIT_TIME_MS);
2036                } catch (InterruptedException e) {
2037                    // Do nothing
2038                }
2039                if (SystemClock.uptimeMillis() > timeEnd) {
2040                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2041                    Slog.wtf(TAG, "cppreopt did not finish!");
2042                    break;
2043                }
2044            }
2045        }
2046    }
2047
2048    public PackageManagerService(Context context, Installer installer,
2049            boolean factoryTest, boolean onlyCore) {
2050        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2051                SystemClock.uptimeMillis());
2052
2053        if (mSdkVersion <= 0) {
2054            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2055        }
2056
2057        mContext = context;
2058        mFactoryTest = factoryTest;
2059        mOnlyCore = onlyCore;
2060        mMetrics = new DisplayMetrics();
2061        mSettings = new Settings(mPackages);
2062        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2063                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2064        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2065                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2066        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2067                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2068        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2069                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2070        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2071                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2072        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2073                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2074
2075        String separateProcesses = SystemProperties.get("debug.separate_processes");
2076        if (separateProcesses != null && separateProcesses.length() > 0) {
2077            if ("*".equals(separateProcesses)) {
2078                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2079                mSeparateProcesses = null;
2080                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2081            } else {
2082                mDefParseFlags = 0;
2083                mSeparateProcesses = separateProcesses.split(",");
2084                Slog.w(TAG, "Running with debug.separate_processes: "
2085                        + separateProcesses);
2086            }
2087        } else {
2088            mDefParseFlags = 0;
2089            mSeparateProcesses = null;
2090        }
2091
2092        mInstaller = installer;
2093        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2094                "*dexopt*");
2095        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2096
2097        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2098                FgThread.get().getLooper());
2099
2100        getDefaultDisplayMetrics(context, mMetrics);
2101
2102        SystemConfig systemConfig = SystemConfig.getInstance();
2103        mGlobalGids = systemConfig.getGlobalGids();
2104        mSystemPermissions = systemConfig.getSystemPermissions();
2105        mAvailableFeatures = systemConfig.getAvailableFeatures();
2106
2107        mProtectedPackages = new ProtectedPackages(mContext);
2108
2109        synchronized (mInstallLock) {
2110        // writer
2111        synchronized (mPackages) {
2112            mHandlerThread = new ServiceThread(TAG,
2113                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2114            mHandlerThread.start();
2115            mHandler = new PackageHandler(mHandlerThread.getLooper());
2116            mProcessLoggingHandler = new ProcessLoggingHandler();
2117            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2118
2119            File dataDir = Environment.getDataDirectory();
2120            mAppInstallDir = new File(dataDir, "app");
2121            mAppLib32InstallDir = new File(dataDir, "app-lib");
2122            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2123            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2124            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2125
2126            sUserManager = new UserManagerService(context, this, mPackages);
2127
2128            // Propagate permission configuration in to package manager.
2129            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2130                    = systemConfig.getPermissions();
2131            for (int i=0; i<permConfig.size(); i++) {
2132                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2133                BasePermission bp = mSettings.mPermissions.get(perm.name);
2134                if (bp == null) {
2135                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2136                    mSettings.mPermissions.put(perm.name, bp);
2137                }
2138                if (perm.gids != null) {
2139                    bp.setGids(perm.gids, perm.perUser);
2140                }
2141            }
2142
2143            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2144            for (int i=0; i<libConfig.size(); i++) {
2145                mSharedLibraries.put(libConfig.keyAt(i),
2146                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2147            }
2148
2149            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2150
2151            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2152
2153            if (mFirstBoot) {
2154                requestCopyPreoptedFiles();
2155            }
2156
2157            String customResolverActivity = Resources.getSystem().getString(
2158                    R.string.config_customResolverActivity);
2159            if (TextUtils.isEmpty(customResolverActivity)) {
2160                customResolverActivity = null;
2161            } else {
2162                mCustomResolverComponentName = ComponentName.unflattenFromString(
2163                        customResolverActivity);
2164            }
2165
2166            long startTime = SystemClock.uptimeMillis();
2167
2168            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2169                    startTime);
2170
2171            // Set flag to monitor and not change apk file paths when
2172            // scanning install directories.
2173            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2174
2175            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2176            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2177
2178            if (bootClassPath == null) {
2179                Slog.w(TAG, "No BOOTCLASSPATH found!");
2180            }
2181
2182            if (systemServerClassPath == null) {
2183                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2184            }
2185
2186            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2187            final String[] dexCodeInstructionSets =
2188                    getDexCodeInstructionSets(
2189                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2190
2191            /**
2192             * Ensure all external libraries have had dexopt run on them.
2193             */
2194            if (mSharedLibraries.size() > 0) {
2195                // NOTE: For now, we're compiling these system "shared libraries"
2196                // (and framework jars) into all available architectures. It's possible
2197                // to compile them only when we come across an app that uses them (there's
2198                // already logic for that in scanPackageLI) but that adds some complexity.
2199                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2200                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2201                        final String lib = libEntry.path;
2202                        if (lib == null) {
2203                            continue;
2204                        }
2205
2206                        try {
2207                            // Shared libraries do not have profiles so we perform a full
2208                            // AOT compilation (if needed).
2209                            int dexoptNeeded = DexFile.getDexOptNeeded(
2210                                    lib, dexCodeInstructionSet,
2211                                    getCompilerFilterForReason(REASON_SHARED_APK),
2212                                    false /* newProfile */);
2213                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2214                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2215                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2216                                        getCompilerFilterForReason(REASON_SHARED_APK),
2217                                        StorageManager.UUID_PRIVATE_INTERNAL,
2218                                        SKIP_SHARED_LIBRARY_CHECK);
2219                            }
2220                        } catch (FileNotFoundException e) {
2221                            Slog.w(TAG, "Library not found: " + lib);
2222                        } catch (IOException | InstallerException e) {
2223                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2224                                    + e.getMessage());
2225                        }
2226                    }
2227                }
2228            }
2229
2230            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2231
2232            final VersionInfo ver = mSettings.getInternalVersion();
2233            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2234
2235            // when upgrading from pre-M, promote system app permissions from install to runtime
2236            mPromoteSystemApps =
2237                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2238
2239            // When upgrading from pre-N, we need to handle package extraction like first boot,
2240            // as there is no profiling data available.
2241            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2242
2243            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2244
2245            // save off the names of pre-existing system packages prior to scanning; we don't
2246            // want to automatically grant runtime permissions for new system apps
2247            if (mPromoteSystemApps) {
2248                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2249                while (pkgSettingIter.hasNext()) {
2250                    PackageSetting ps = pkgSettingIter.next();
2251                    if (isSystemApp(ps)) {
2252                        mExistingSystemPackages.add(ps.name);
2253                    }
2254                }
2255            }
2256
2257            // Collect vendor overlay packages.
2258            // (Do this before scanning any apps.)
2259            // For security and version matching reason, only consider
2260            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2261            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2262            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2263                    | PackageParser.PARSE_IS_SYSTEM
2264                    | PackageParser.PARSE_IS_SYSTEM_DIR
2265                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2266
2267            // Find base frameworks (resource packages without code).
2268            scanDirTracedLI(frameworkDir, mDefParseFlags
2269                    | PackageParser.PARSE_IS_SYSTEM
2270                    | PackageParser.PARSE_IS_SYSTEM_DIR
2271                    | PackageParser.PARSE_IS_PRIVILEGED,
2272                    scanFlags | SCAN_NO_DEX, 0);
2273
2274            // Collected privileged system packages.
2275            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2276            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2277                    | PackageParser.PARSE_IS_SYSTEM
2278                    | PackageParser.PARSE_IS_SYSTEM_DIR
2279                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2280
2281            // Collect ordinary system packages.
2282            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2283            scanDirTracedLI(systemAppDir, mDefParseFlags
2284                    | PackageParser.PARSE_IS_SYSTEM
2285                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2286
2287            // Collect all vendor packages.
2288            File vendorAppDir = new File("/vendor/app");
2289            try {
2290                vendorAppDir = vendorAppDir.getCanonicalFile();
2291            } catch (IOException e) {
2292                // failed to look up canonical path, continue with original one
2293            }
2294            scanDirTracedLI(vendorAppDir, mDefParseFlags
2295                    | PackageParser.PARSE_IS_SYSTEM
2296                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2297
2298            // Collect all OEM packages.
2299            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2300            scanDirTracedLI(oemAppDir, mDefParseFlags
2301                    | PackageParser.PARSE_IS_SYSTEM
2302                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2303
2304            // Prune any system packages that no longer exist.
2305            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2306            if (!mOnlyCore) {
2307                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2308                while (psit.hasNext()) {
2309                    PackageSetting ps = psit.next();
2310
2311                    /*
2312                     * If this is not a system app, it can't be a
2313                     * disable system app.
2314                     */
2315                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2316                        continue;
2317                    }
2318
2319                    /*
2320                     * If the package is scanned, it's not erased.
2321                     */
2322                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2323                    if (scannedPkg != null) {
2324                        /*
2325                         * If the system app is both scanned and in the
2326                         * disabled packages list, then it must have been
2327                         * added via OTA. Remove it from the currently
2328                         * scanned package so the previously user-installed
2329                         * application can be scanned.
2330                         */
2331                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2332                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2333                                    + ps.name + "; removing system app.  Last known codePath="
2334                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2335                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2336                                    + scannedPkg.mVersionCode);
2337                            removePackageLI(scannedPkg, true);
2338                            mExpectingBetter.put(ps.name, ps.codePath);
2339                        }
2340
2341                        continue;
2342                    }
2343
2344                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2345                        psit.remove();
2346                        logCriticalInfo(Log.WARN, "System package " + ps.name
2347                                + " no longer exists; it's data will be wiped");
2348                        // Actual deletion of code and data will be handled by later
2349                        // reconciliation step
2350                    } else {
2351                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2352                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2353                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2354                        }
2355                    }
2356                }
2357            }
2358
2359            //look for any incomplete package installations
2360            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2361            for (int i = 0; i < deletePkgsList.size(); i++) {
2362                // Actual deletion of code and data will be handled by later
2363                // reconciliation step
2364                final String packageName = deletePkgsList.get(i).name;
2365                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2366                synchronized (mPackages) {
2367                    mSettings.removePackageLPw(packageName);
2368                }
2369            }
2370
2371            //delete tmp files
2372            deleteTempPackageFiles();
2373
2374            // Remove any shared userIDs that have no associated packages
2375            mSettings.pruneSharedUsersLPw();
2376
2377            if (!mOnlyCore) {
2378                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2379                        SystemClock.uptimeMillis());
2380                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2381
2382                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2383                        | PackageParser.PARSE_FORWARD_LOCK,
2384                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2385
2386                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2387                        | PackageParser.PARSE_IS_EPHEMERAL,
2388                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2389
2390                /**
2391                 * Remove disable package settings for any updated system
2392                 * apps that were removed via an OTA. If they're not a
2393                 * previously-updated app, remove them completely.
2394                 * Otherwise, just revoke their system-level permissions.
2395                 */
2396                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2397                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2398                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2399
2400                    String msg;
2401                    if (deletedPkg == null) {
2402                        msg = "Updated system package " + deletedAppName
2403                                + " no longer exists; it's data will be wiped";
2404                        // Actual deletion of code and data will be handled by later
2405                        // reconciliation step
2406                    } else {
2407                        msg = "Updated system app + " + deletedAppName
2408                                + " no longer present; removing system privileges for "
2409                                + deletedAppName;
2410
2411                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2412
2413                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2414                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2415                    }
2416                    logCriticalInfo(Log.WARN, msg);
2417                }
2418
2419                /**
2420                 * Make sure all system apps that we expected to appear on
2421                 * the userdata partition actually showed up. If they never
2422                 * appeared, crawl back and revive the system version.
2423                 */
2424                for (int i = 0; i < mExpectingBetter.size(); i++) {
2425                    final String packageName = mExpectingBetter.keyAt(i);
2426                    if (!mPackages.containsKey(packageName)) {
2427                        final File scanFile = mExpectingBetter.valueAt(i);
2428
2429                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2430                                + " but never showed up; reverting to system");
2431
2432                        int reparseFlags = mDefParseFlags;
2433                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2434                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2435                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2436                                    | PackageParser.PARSE_IS_PRIVILEGED;
2437                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2438                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2439                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2440                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2441                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2442                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2443                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2444                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2445                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2446                        } else {
2447                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2448                            continue;
2449                        }
2450
2451                        mSettings.enableSystemPackageLPw(packageName);
2452
2453                        try {
2454                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2455                        } catch (PackageManagerException e) {
2456                            Slog.e(TAG, "Failed to parse original system package: "
2457                                    + e.getMessage());
2458                        }
2459                    }
2460                }
2461            }
2462            mExpectingBetter.clear();
2463
2464            // Resolve protected action filters. Only the setup wizard is allowed to
2465            // have a high priority filter for these actions.
2466            mSetupWizardPackage = getSetupWizardPackageName();
2467            if (mProtectedFilters.size() > 0) {
2468                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2469                    Slog.i(TAG, "No setup wizard;"
2470                        + " All protected intents capped to priority 0");
2471                }
2472                for (ActivityIntentInfo filter : mProtectedFilters) {
2473                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2474                        if (DEBUG_FILTERS) {
2475                            Slog.i(TAG, "Found setup wizard;"
2476                                + " allow priority " + filter.getPriority() + ";"
2477                                + " package: " + filter.activity.info.packageName
2478                                + " activity: " + filter.activity.className
2479                                + " priority: " + filter.getPriority());
2480                        }
2481                        // skip setup wizard; allow it to keep the high priority filter
2482                        continue;
2483                    }
2484                    Slog.w(TAG, "Protected action; cap priority to 0;"
2485                            + " package: " + filter.activity.info.packageName
2486                            + " activity: " + filter.activity.className
2487                            + " origPrio: " + filter.getPriority());
2488                    filter.setPriority(0);
2489                }
2490            }
2491            mDeferProtectedFilters = false;
2492            mProtectedFilters.clear();
2493
2494            // Now that we know all of the shared libraries, update all clients to have
2495            // the correct library paths.
2496            updateAllSharedLibrariesLPw();
2497
2498            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2499                // NOTE: We ignore potential failures here during a system scan (like
2500                // the rest of the commands above) because there's precious little we
2501                // can do about it. A settings error is reported, though.
2502                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2503                        false /* boot complete */);
2504            }
2505
2506            // Now that we know all the packages we are keeping,
2507            // read and update their last usage times.
2508            mPackageUsage.read(mPackages);
2509            mCompilerStats.read();
2510
2511            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2512                    SystemClock.uptimeMillis());
2513            Slog.i(TAG, "Time to scan packages: "
2514                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2515                    + " seconds");
2516
2517            // If the platform SDK has changed since the last time we booted,
2518            // we need to re-grant app permission to catch any new ones that
2519            // appear.  This is really a hack, and means that apps can in some
2520            // cases get permissions that the user didn't initially explicitly
2521            // allow...  it would be nice to have some better way to handle
2522            // this situation.
2523            int updateFlags = UPDATE_PERMISSIONS_ALL;
2524            if (ver.sdkVersion != mSdkVersion) {
2525                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2526                        + mSdkVersion + "; regranting permissions for internal storage");
2527                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2528            }
2529            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2530            ver.sdkVersion = mSdkVersion;
2531
2532            // If this is the first boot or an update from pre-M, and it is a normal
2533            // boot, then we need to initialize the default preferred apps across
2534            // all defined users.
2535            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2536                for (UserInfo user : sUserManager.getUsers(true)) {
2537                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2538                    applyFactoryDefaultBrowserLPw(user.id);
2539                    primeDomainVerificationsLPw(user.id);
2540                }
2541            }
2542
2543            // Prepare storage for system user really early during boot,
2544            // since core system apps like SettingsProvider and SystemUI
2545            // can't wait for user to start
2546            final int storageFlags;
2547            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2548                storageFlags = StorageManager.FLAG_STORAGE_DE;
2549            } else {
2550                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2551            }
2552            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2553                    storageFlags);
2554
2555            // If this is first boot after an OTA, and a normal boot, then
2556            // we need to clear code cache directories.
2557            // Note that we do *not* clear the application profiles. These remain valid
2558            // across OTAs and are used to drive profile verification (post OTA) and
2559            // profile compilation (without waiting to collect a fresh set of profiles).
2560            if (mIsUpgrade && !onlyCore) {
2561                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2562                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2563                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2564                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2565                        // No apps are running this early, so no need to freeze
2566                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2567                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2568                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2569                    }
2570                }
2571                ver.fingerprint = Build.FINGERPRINT;
2572            }
2573
2574            checkDefaultBrowser();
2575
2576            // clear only after permissions and other defaults have been updated
2577            mExistingSystemPackages.clear();
2578            mPromoteSystemApps = false;
2579
2580            // All the changes are done during package scanning.
2581            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2582
2583            // can downgrade to reader
2584            mSettings.writeLPr();
2585
2586            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2587            // early on (before the package manager declares itself as early) because other
2588            // components in the system server might ask for package contexts for these apps.
2589            //
2590            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2591            // (i.e, that the data partition is unavailable).
2592            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2593                long start = System.nanoTime();
2594                List<PackageParser.Package> coreApps = new ArrayList<>();
2595                for (PackageParser.Package pkg : mPackages.values()) {
2596                    if (pkg.coreApp) {
2597                        coreApps.add(pkg);
2598                    }
2599                }
2600
2601                int[] stats = performDexOptUpgrade(coreApps, false,
2602                        getCompilerFilterForReason(REASON_CORE_APP));
2603
2604                final int elapsedTimeSeconds =
2605                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2606                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2607
2608                if (DEBUG_DEXOPT) {
2609                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2610                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2611                }
2612
2613
2614                // TODO: Should we log these stats to tron too ?
2615                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2616                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2617                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2618                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2619            }
2620
2621            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2622                    SystemClock.uptimeMillis());
2623
2624            if (!mOnlyCore) {
2625                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2626                mRequiredInstallerPackage = getRequiredInstallerLPr();
2627                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2628                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2629                        mIntentFilterVerifierComponent);
2630                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2631                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2632                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2633                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2634            } else {
2635                mRequiredVerifierPackage = null;
2636                mRequiredInstallerPackage = null;
2637                mIntentFilterVerifierComponent = null;
2638                mIntentFilterVerifier = null;
2639                mServicesSystemSharedLibraryPackageName = null;
2640                mSharedSystemSharedLibraryPackageName = null;
2641            }
2642
2643            mInstallerService = new PackageInstallerService(context, this);
2644
2645            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2646            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2647            // both the installer and resolver must be present to enable ephemeral
2648            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2649                if (DEBUG_EPHEMERAL) {
2650                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2651                            + " installer:" + ephemeralInstallerComponent);
2652                }
2653                mEphemeralResolverComponent = ephemeralResolverComponent;
2654                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2655                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2656                mEphemeralResolverConnection =
2657                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2658            } else {
2659                if (DEBUG_EPHEMERAL) {
2660                    final String missingComponent =
2661                            (ephemeralResolverComponent == null)
2662                            ? (ephemeralInstallerComponent == null)
2663                                    ? "resolver and installer"
2664                                    : "resolver"
2665                            : "installer";
2666                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2667                }
2668                mEphemeralResolverComponent = null;
2669                mEphemeralInstallerComponent = null;
2670                mEphemeralResolverConnection = null;
2671            }
2672
2673            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2674        } // synchronized (mPackages)
2675        } // synchronized (mInstallLock)
2676
2677        // Now after opening every single application zip, make sure they
2678        // are all flushed.  Not really needed, but keeps things nice and
2679        // tidy.
2680        Runtime.getRuntime().gc();
2681
2682        // The initial scanning above does many calls into installd while
2683        // holding the mPackages lock, but we're mostly interested in yelling
2684        // once we have a booted system.
2685        mInstaller.setWarnIfHeld(mPackages);
2686
2687        // Expose private service for system components to use.
2688        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2689    }
2690
2691    @Override
2692    public boolean isFirstBoot() {
2693        return mFirstBoot;
2694    }
2695
2696    @Override
2697    public boolean isOnlyCoreApps() {
2698        return mOnlyCore;
2699    }
2700
2701    @Override
2702    public boolean isUpgrade() {
2703        return mIsUpgrade;
2704    }
2705
2706    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2707        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2708
2709        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2710                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2711                UserHandle.USER_SYSTEM);
2712        if (matches.size() == 1) {
2713            return matches.get(0).getComponentInfo().packageName;
2714        } else {
2715            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2716            return null;
2717        }
2718    }
2719
2720    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2721        synchronized (mPackages) {
2722            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2723            if (libraryEntry == null) {
2724                throw new IllegalStateException("Missing required shared library:" + libraryName);
2725            }
2726            return libraryEntry.apk;
2727        }
2728    }
2729
2730    private @NonNull String getRequiredInstallerLPr() {
2731        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2732        intent.addCategory(Intent.CATEGORY_DEFAULT);
2733        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2734
2735        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2736                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2737                UserHandle.USER_SYSTEM);
2738        if (matches.size() == 1) {
2739            ResolveInfo resolveInfo = matches.get(0);
2740            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2741                throw new RuntimeException("The installer must be a privileged app");
2742            }
2743            return matches.get(0).getComponentInfo().packageName;
2744        } else {
2745            throw new RuntimeException("There must be exactly one installer; found " + matches);
2746        }
2747    }
2748
2749    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2750        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2751
2752        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2753                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2754                UserHandle.USER_SYSTEM);
2755        ResolveInfo best = null;
2756        final int N = matches.size();
2757        for (int i = 0; i < N; i++) {
2758            final ResolveInfo cur = matches.get(i);
2759            final String packageName = cur.getComponentInfo().packageName;
2760            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2761                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2762                continue;
2763            }
2764
2765            if (best == null || cur.priority > best.priority) {
2766                best = cur;
2767            }
2768        }
2769
2770        if (best != null) {
2771            return best.getComponentInfo().getComponentName();
2772        } else {
2773            throw new RuntimeException("There must be at least one intent filter verifier");
2774        }
2775    }
2776
2777    private @Nullable ComponentName getEphemeralResolverLPr() {
2778        final String[] packageArray =
2779                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2780        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2781            if (DEBUG_EPHEMERAL) {
2782                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2783            }
2784            return null;
2785        }
2786
2787        final int resolveFlags =
2788                MATCH_DIRECT_BOOT_AWARE
2789                | MATCH_DIRECT_BOOT_UNAWARE
2790                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2791        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2792        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2793                resolveFlags, UserHandle.USER_SYSTEM);
2794
2795        final int N = resolvers.size();
2796        if (N == 0) {
2797            if (DEBUG_EPHEMERAL) {
2798                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2799            }
2800            return null;
2801        }
2802
2803        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2804        for (int i = 0; i < N; i++) {
2805            final ResolveInfo info = resolvers.get(i);
2806
2807            if (info.serviceInfo == null) {
2808                continue;
2809            }
2810
2811            final String packageName = info.serviceInfo.packageName;
2812            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2813                if (DEBUG_EPHEMERAL) {
2814                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2815                            + " pkg: " + packageName + ", info:" + info);
2816                }
2817                continue;
2818            }
2819
2820            if (DEBUG_EPHEMERAL) {
2821                Slog.v(TAG, "Ephemeral resolver found;"
2822                        + " pkg: " + packageName + ", info:" + info);
2823            }
2824            return new ComponentName(packageName, info.serviceInfo.name);
2825        }
2826        if (DEBUG_EPHEMERAL) {
2827            Slog.v(TAG, "Ephemeral resolver NOT found");
2828        }
2829        return null;
2830    }
2831
2832    private @Nullable ComponentName getEphemeralInstallerLPr() {
2833        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2834        intent.addCategory(Intent.CATEGORY_DEFAULT);
2835        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2836
2837        final int resolveFlags =
2838                MATCH_DIRECT_BOOT_AWARE
2839                | MATCH_DIRECT_BOOT_UNAWARE
2840                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2841        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2842                resolveFlags, UserHandle.USER_SYSTEM);
2843        if (matches.size() == 0) {
2844            return null;
2845        } else if (matches.size() == 1) {
2846            return matches.get(0).getComponentInfo().getComponentName();
2847        } else {
2848            throw new RuntimeException(
2849                    "There must be at most one ephemeral installer; found " + matches);
2850        }
2851    }
2852
2853    private void primeDomainVerificationsLPw(int userId) {
2854        if (DEBUG_DOMAIN_VERIFICATION) {
2855            Slog.d(TAG, "Priming domain verifications in user " + userId);
2856        }
2857
2858        SystemConfig systemConfig = SystemConfig.getInstance();
2859        ArraySet<String> packages = systemConfig.getLinkedApps();
2860        ArraySet<String> domains = new ArraySet<String>();
2861
2862        for (String packageName : packages) {
2863            PackageParser.Package pkg = mPackages.get(packageName);
2864            if (pkg != null) {
2865                if (!pkg.isSystemApp()) {
2866                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2867                    continue;
2868                }
2869
2870                domains.clear();
2871                for (PackageParser.Activity a : pkg.activities) {
2872                    for (ActivityIntentInfo filter : a.intents) {
2873                        if (hasValidDomains(filter)) {
2874                            domains.addAll(filter.getHostsList());
2875                        }
2876                    }
2877                }
2878
2879                if (domains.size() > 0) {
2880                    if (DEBUG_DOMAIN_VERIFICATION) {
2881                        Slog.v(TAG, "      + " + packageName);
2882                    }
2883                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2884                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2885                    // and then 'always' in the per-user state actually used for intent resolution.
2886                    final IntentFilterVerificationInfo ivi;
2887                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2888                            new ArrayList<String>(domains));
2889                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2890                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2891                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2892                } else {
2893                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2894                            + "' does not handle web links");
2895                }
2896            } else {
2897                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2898            }
2899        }
2900
2901        scheduleWritePackageRestrictionsLocked(userId);
2902        scheduleWriteSettingsLocked();
2903    }
2904
2905    private void applyFactoryDefaultBrowserLPw(int userId) {
2906        // The default browser app's package name is stored in a string resource,
2907        // with a product-specific overlay used for vendor customization.
2908        String browserPkg = mContext.getResources().getString(
2909                com.android.internal.R.string.default_browser);
2910        if (!TextUtils.isEmpty(browserPkg)) {
2911            // non-empty string => required to be a known package
2912            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2913            if (ps == null) {
2914                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2915                browserPkg = null;
2916            } else {
2917                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2918            }
2919        }
2920
2921        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2922        // default.  If there's more than one, just leave everything alone.
2923        if (browserPkg == null) {
2924            calculateDefaultBrowserLPw(userId);
2925        }
2926    }
2927
2928    private void calculateDefaultBrowserLPw(int userId) {
2929        List<String> allBrowsers = resolveAllBrowserApps(userId);
2930        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2931        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2932    }
2933
2934    private List<String> resolveAllBrowserApps(int userId) {
2935        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2936        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2937                PackageManager.MATCH_ALL, userId);
2938
2939        final int count = list.size();
2940        List<String> result = new ArrayList<String>(count);
2941        for (int i=0; i<count; i++) {
2942            ResolveInfo info = list.get(i);
2943            if (info.activityInfo == null
2944                    || !info.handleAllWebDataURI
2945                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2946                    || result.contains(info.activityInfo.packageName)) {
2947                continue;
2948            }
2949            result.add(info.activityInfo.packageName);
2950        }
2951
2952        return result;
2953    }
2954
2955    private boolean packageIsBrowser(String packageName, int userId) {
2956        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2957                PackageManager.MATCH_ALL, userId);
2958        final int N = list.size();
2959        for (int i = 0; i < N; i++) {
2960            ResolveInfo info = list.get(i);
2961            if (packageName.equals(info.activityInfo.packageName)) {
2962                return true;
2963            }
2964        }
2965        return false;
2966    }
2967
2968    private void checkDefaultBrowser() {
2969        final int myUserId = UserHandle.myUserId();
2970        final String packageName = getDefaultBrowserPackageName(myUserId);
2971        if (packageName != null) {
2972            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2973            if (info == null) {
2974                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2975                synchronized (mPackages) {
2976                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2977                }
2978            }
2979        }
2980    }
2981
2982    @Override
2983    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2984            throws RemoteException {
2985        try {
2986            return super.onTransact(code, data, reply, flags);
2987        } catch (RuntimeException e) {
2988            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2989                Slog.wtf(TAG, "Package Manager Crash", e);
2990            }
2991            throw e;
2992        }
2993    }
2994
2995    static int[] appendInts(int[] cur, int[] add) {
2996        if (add == null) return cur;
2997        if (cur == null) return add;
2998        final int N = add.length;
2999        for (int i=0; i<N; i++) {
3000            cur = appendInt(cur, add[i]);
3001        }
3002        return cur;
3003    }
3004
3005    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3006        if (!sUserManager.exists(userId)) return null;
3007        if (ps == null) {
3008            return null;
3009        }
3010        final PackageParser.Package p = ps.pkg;
3011        if (p == null) {
3012            return null;
3013        }
3014
3015        final PermissionsState permissionsState = ps.getPermissionsState();
3016
3017        // Compute GIDs only if requested
3018        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3019                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3020        // Compute granted permissions only if package has requested permissions
3021        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3022                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3023        final PackageUserState state = ps.readUserState(userId);
3024
3025        return PackageParser.generatePackageInfo(p, gids, flags,
3026                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3027    }
3028
3029    @Override
3030    public void checkPackageStartable(String packageName, int userId) {
3031        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3032
3033        synchronized (mPackages) {
3034            final PackageSetting ps = mSettings.mPackages.get(packageName);
3035            if (ps == null) {
3036                throw new SecurityException("Package " + packageName + " was not found!");
3037            }
3038
3039            if (!ps.getInstalled(userId)) {
3040                throw new SecurityException(
3041                        "Package " + packageName + " was not installed for user " + userId + "!");
3042            }
3043
3044            if (mSafeMode && !ps.isSystem()) {
3045                throw new SecurityException("Package " + packageName + " not a system app!");
3046            }
3047
3048            if (mFrozenPackages.contains(packageName)) {
3049                throw new SecurityException("Package " + packageName + " is currently frozen!");
3050            }
3051
3052            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3053                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3054                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3055            }
3056        }
3057    }
3058
3059    @Override
3060    public boolean isPackageAvailable(String packageName, int userId) {
3061        if (!sUserManager.exists(userId)) return false;
3062        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3063                false /* requireFullPermission */, false /* checkShell */, "is package available");
3064        synchronized (mPackages) {
3065            PackageParser.Package p = mPackages.get(packageName);
3066            if (p != null) {
3067                final PackageSetting ps = (PackageSetting) p.mExtras;
3068                if (ps != null) {
3069                    final PackageUserState state = ps.readUserState(userId);
3070                    if (state != null) {
3071                        return PackageParser.isAvailable(state);
3072                    }
3073                }
3074            }
3075        }
3076        return false;
3077    }
3078
3079    @Override
3080    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3081        if (!sUserManager.exists(userId)) return null;
3082        flags = updateFlagsForPackage(flags, userId, packageName);
3083        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3084                false /* requireFullPermission */, false /* checkShell */, "get package info");
3085        // reader
3086        synchronized (mPackages) {
3087            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3088            PackageParser.Package p = null;
3089            if (matchFactoryOnly) {
3090                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3091                if (ps != null) {
3092                    return generatePackageInfo(ps, flags, userId);
3093                }
3094            }
3095            if (p == null) {
3096                p = mPackages.get(packageName);
3097                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3098                    return null;
3099                }
3100            }
3101            if (DEBUG_PACKAGE_INFO)
3102                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3103            if (p != null) {
3104                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3105            }
3106            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3107                final PackageSetting ps = mSettings.mPackages.get(packageName);
3108                return generatePackageInfo(ps, flags, userId);
3109            }
3110        }
3111        return null;
3112    }
3113
3114    @Override
3115    public String[] currentToCanonicalPackageNames(String[] names) {
3116        String[] out = new String[names.length];
3117        // reader
3118        synchronized (mPackages) {
3119            for (int i=names.length-1; i>=0; i--) {
3120                PackageSetting ps = mSettings.mPackages.get(names[i]);
3121                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3122            }
3123        }
3124        return out;
3125    }
3126
3127    @Override
3128    public String[] canonicalToCurrentPackageNames(String[] names) {
3129        String[] out = new String[names.length];
3130        // reader
3131        synchronized (mPackages) {
3132            for (int i=names.length-1; i>=0; i--) {
3133                String cur = mSettings.mRenamedPackages.get(names[i]);
3134                out[i] = cur != null ? cur : names[i];
3135            }
3136        }
3137        return out;
3138    }
3139
3140    @Override
3141    public int getPackageUid(String packageName, int flags, int userId) {
3142        if (!sUserManager.exists(userId)) return -1;
3143        flags = updateFlagsForPackage(flags, userId, packageName);
3144        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3145                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3146
3147        // reader
3148        synchronized (mPackages) {
3149            final PackageParser.Package p = mPackages.get(packageName);
3150            if (p != null && p.isMatch(flags)) {
3151                return UserHandle.getUid(userId, p.applicationInfo.uid);
3152            }
3153            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3154                final PackageSetting ps = mSettings.mPackages.get(packageName);
3155                if (ps != null && ps.isMatch(flags)) {
3156                    return UserHandle.getUid(userId, ps.appId);
3157                }
3158            }
3159        }
3160
3161        return -1;
3162    }
3163
3164    @Override
3165    public int[] getPackageGids(String packageName, int flags, int userId) {
3166        if (!sUserManager.exists(userId)) return null;
3167        flags = updateFlagsForPackage(flags, userId, packageName);
3168        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3169                false /* requireFullPermission */, false /* checkShell */,
3170                "getPackageGids");
3171
3172        // reader
3173        synchronized (mPackages) {
3174            final PackageParser.Package p = mPackages.get(packageName);
3175            if (p != null && p.isMatch(flags)) {
3176                PackageSetting ps = (PackageSetting) p.mExtras;
3177                return ps.getPermissionsState().computeGids(userId);
3178            }
3179            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3180                final PackageSetting ps = mSettings.mPackages.get(packageName);
3181                if (ps != null && ps.isMatch(flags)) {
3182                    return ps.getPermissionsState().computeGids(userId);
3183                }
3184            }
3185        }
3186
3187        return null;
3188    }
3189
3190    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3191        if (bp.perm != null) {
3192            return PackageParser.generatePermissionInfo(bp.perm, flags);
3193        }
3194        PermissionInfo pi = new PermissionInfo();
3195        pi.name = bp.name;
3196        pi.packageName = bp.sourcePackage;
3197        pi.nonLocalizedLabel = bp.name;
3198        pi.protectionLevel = bp.protectionLevel;
3199        return pi;
3200    }
3201
3202    @Override
3203    public PermissionInfo getPermissionInfo(String name, int flags) {
3204        // reader
3205        synchronized (mPackages) {
3206            final BasePermission p = mSettings.mPermissions.get(name);
3207            if (p != null) {
3208                return generatePermissionInfo(p, flags);
3209            }
3210            return null;
3211        }
3212    }
3213
3214    @Override
3215    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3216            int flags) {
3217        // reader
3218        synchronized (mPackages) {
3219            if (group != null && !mPermissionGroups.containsKey(group)) {
3220                // This is thrown as NameNotFoundException
3221                return null;
3222            }
3223
3224            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3225            for (BasePermission p : mSettings.mPermissions.values()) {
3226                if (group == null) {
3227                    if (p.perm == null || p.perm.info.group == null) {
3228                        out.add(generatePermissionInfo(p, flags));
3229                    }
3230                } else {
3231                    if (p.perm != null && group.equals(p.perm.info.group)) {
3232                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3233                    }
3234                }
3235            }
3236            return new ParceledListSlice<>(out);
3237        }
3238    }
3239
3240    @Override
3241    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3242        // reader
3243        synchronized (mPackages) {
3244            return PackageParser.generatePermissionGroupInfo(
3245                    mPermissionGroups.get(name), flags);
3246        }
3247    }
3248
3249    @Override
3250    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3251        // reader
3252        synchronized (mPackages) {
3253            final int N = mPermissionGroups.size();
3254            ArrayList<PermissionGroupInfo> out
3255                    = new ArrayList<PermissionGroupInfo>(N);
3256            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3257                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3258            }
3259            return new ParceledListSlice<>(out);
3260        }
3261    }
3262
3263    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3264            int userId) {
3265        if (!sUserManager.exists(userId)) return null;
3266        PackageSetting ps = mSettings.mPackages.get(packageName);
3267        if (ps != null) {
3268            if (ps.pkg == null) {
3269                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3270                if (pInfo != null) {
3271                    return pInfo.applicationInfo;
3272                }
3273                return null;
3274            }
3275            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3276                    ps.readUserState(userId), userId);
3277        }
3278        return null;
3279    }
3280
3281    @Override
3282    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3283        if (!sUserManager.exists(userId)) return null;
3284        flags = updateFlagsForApplication(flags, userId, packageName);
3285        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3286                false /* requireFullPermission */, false /* checkShell */, "get application info");
3287        // writer
3288        synchronized (mPackages) {
3289            PackageParser.Package p = mPackages.get(packageName);
3290            if (DEBUG_PACKAGE_INFO) Log.v(
3291                    TAG, "getApplicationInfo " + packageName
3292                    + ": " + p);
3293            if (p != null) {
3294                PackageSetting ps = mSettings.mPackages.get(packageName);
3295                if (ps == null) return null;
3296                // Note: isEnabledLP() does not apply here - always return info
3297                return PackageParser.generateApplicationInfo(
3298                        p, flags, ps.readUserState(userId), userId);
3299            }
3300            if ("android".equals(packageName)||"system".equals(packageName)) {
3301                return mAndroidApplication;
3302            }
3303            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3304                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3305            }
3306        }
3307        return null;
3308    }
3309
3310    @Override
3311    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3312            final IPackageDataObserver observer) {
3313        mContext.enforceCallingOrSelfPermission(
3314                android.Manifest.permission.CLEAR_APP_CACHE, null);
3315        // Queue up an async operation since clearing cache may take a little while.
3316        mHandler.post(new Runnable() {
3317            public void run() {
3318                mHandler.removeCallbacks(this);
3319                boolean success = true;
3320                synchronized (mInstallLock) {
3321                    try {
3322                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3323                    } catch (InstallerException e) {
3324                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3325                        success = false;
3326                    }
3327                }
3328                if (observer != null) {
3329                    try {
3330                        observer.onRemoveCompleted(null, success);
3331                    } catch (RemoteException e) {
3332                        Slog.w(TAG, "RemoveException when invoking call back");
3333                    }
3334                }
3335            }
3336        });
3337    }
3338
3339    @Override
3340    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3341            final IntentSender pi) {
3342        mContext.enforceCallingOrSelfPermission(
3343                android.Manifest.permission.CLEAR_APP_CACHE, null);
3344        // Queue up an async operation since clearing cache may take a little while.
3345        mHandler.post(new Runnable() {
3346            public void run() {
3347                mHandler.removeCallbacks(this);
3348                boolean success = true;
3349                synchronized (mInstallLock) {
3350                    try {
3351                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3352                    } catch (InstallerException e) {
3353                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3354                        success = false;
3355                    }
3356                }
3357                if(pi != null) {
3358                    try {
3359                        // Callback via pending intent
3360                        int code = success ? 1 : 0;
3361                        pi.sendIntent(null, code, null,
3362                                null, null);
3363                    } catch (SendIntentException e1) {
3364                        Slog.i(TAG, "Failed to send pending intent");
3365                    }
3366                }
3367            }
3368        });
3369    }
3370
3371    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3372        synchronized (mInstallLock) {
3373            try {
3374                mInstaller.freeCache(volumeUuid, freeStorageSize);
3375            } catch (InstallerException e) {
3376                throw new IOException("Failed to free enough space", e);
3377            }
3378        }
3379    }
3380
3381    /**
3382     * Update given flags based on encryption status of current user.
3383     */
3384    private int updateFlags(int flags, int userId) {
3385        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3386                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3387            // Caller expressed an explicit opinion about what encryption
3388            // aware/unaware components they want to see, so fall through and
3389            // give them what they want
3390        } else {
3391            // Caller expressed no opinion, so match based on user state
3392            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3393                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3394            } else {
3395                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3396            }
3397        }
3398        return flags;
3399    }
3400
3401    private UserManagerInternal getUserManagerInternal() {
3402        if (mUserManagerInternal == null) {
3403            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3404        }
3405        return mUserManagerInternal;
3406    }
3407
3408    /**
3409     * Update given flags when being used to request {@link PackageInfo}.
3410     */
3411    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3412        boolean triaged = true;
3413        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3414                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3415            // Caller is asking for component details, so they'd better be
3416            // asking for specific encryption matching behavior, or be triaged
3417            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3418                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3419                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3420                triaged = false;
3421            }
3422        }
3423        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3424                | PackageManager.MATCH_SYSTEM_ONLY
3425                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3426            triaged = false;
3427        }
3428        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3429            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3430                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3431        }
3432        return updateFlags(flags, userId);
3433    }
3434
3435    /**
3436     * Update given flags when being used to request {@link ApplicationInfo}.
3437     */
3438    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3439        return updateFlagsForPackage(flags, userId, cookie);
3440    }
3441
3442    /**
3443     * Update given flags when being used to request {@link ComponentInfo}.
3444     */
3445    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3446        if (cookie instanceof Intent) {
3447            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3448                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3449            }
3450        }
3451
3452        boolean triaged = true;
3453        // Caller is asking for component details, so they'd better be
3454        // asking for specific encryption matching behavior, or be triaged
3455        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3456                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3457                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3458            triaged = false;
3459        }
3460        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3461            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3462                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3463        }
3464
3465        return updateFlags(flags, userId);
3466    }
3467
3468    /**
3469     * Update given flags when being used to request {@link ResolveInfo}.
3470     */
3471    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3472        // Safe mode means we shouldn't match any third-party components
3473        if (mSafeMode) {
3474            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3475        }
3476
3477        return updateFlagsForComponent(flags, userId, cookie);
3478    }
3479
3480    @Override
3481    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3482        if (!sUserManager.exists(userId)) return null;
3483        flags = updateFlagsForComponent(flags, userId, component);
3484        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3485                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3486        synchronized (mPackages) {
3487            PackageParser.Activity a = mActivities.mActivities.get(component);
3488
3489            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3490            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3491                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3492                if (ps == null) return null;
3493                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3494                        userId);
3495            }
3496            if (mResolveComponentName.equals(component)) {
3497                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3498                        new PackageUserState(), userId);
3499            }
3500        }
3501        return null;
3502    }
3503
3504    @Override
3505    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3506            String resolvedType) {
3507        synchronized (mPackages) {
3508            if (component.equals(mResolveComponentName)) {
3509                // The resolver supports EVERYTHING!
3510                return true;
3511            }
3512            PackageParser.Activity a = mActivities.mActivities.get(component);
3513            if (a == null) {
3514                return false;
3515            }
3516            for (int i=0; i<a.intents.size(); i++) {
3517                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3518                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3519                    return true;
3520                }
3521            }
3522            return false;
3523        }
3524    }
3525
3526    @Override
3527    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3528        if (!sUserManager.exists(userId)) return null;
3529        flags = updateFlagsForComponent(flags, userId, component);
3530        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3531                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3532        synchronized (mPackages) {
3533            PackageParser.Activity a = mReceivers.mActivities.get(component);
3534            if (DEBUG_PACKAGE_INFO) Log.v(
3535                TAG, "getReceiverInfo " + component + ": " + a);
3536            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3537                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3538                if (ps == null) return null;
3539                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3540                        userId);
3541            }
3542        }
3543        return null;
3544    }
3545
3546    @Override
3547    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3548        if (!sUserManager.exists(userId)) return null;
3549        flags = updateFlagsForComponent(flags, userId, component);
3550        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3551                false /* requireFullPermission */, false /* checkShell */, "get service info");
3552        synchronized (mPackages) {
3553            PackageParser.Service s = mServices.mServices.get(component);
3554            if (DEBUG_PACKAGE_INFO) Log.v(
3555                TAG, "getServiceInfo " + component + ": " + s);
3556            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3557                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3558                if (ps == null) return null;
3559                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3560                        userId);
3561            }
3562        }
3563        return null;
3564    }
3565
3566    @Override
3567    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3568        if (!sUserManager.exists(userId)) return null;
3569        flags = updateFlagsForComponent(flags, userId, component);
3570        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3571                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3572        synchronized (mPackages) {
3573            PackageParser.Provider p = mProviders.mProviders.get(component);
3574            if (DEBUG_PACKAGE_INFO) Log.v(
3575                TAG, "getProviderInfo " + component + ": " + p);
3576            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3577                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3578                if (ps == null) return null;
3579                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3580                        userId);
3581            }
3582        }
3583        return null;
3584    }
3585
3586    @Override
3587    public String[] getSystemSharedLibraryNames() {
3588        Set<String> libSet;
3589        synchronized (mPackages) {
3590            libSet = mSharedLibraries.keySet();
3591            int size = libSet.size();
3592            if (size > 0) {
3593                String[] libs = new String[size];
3594                libSet.toArray(libs);
3595                return libs;
3596            }
3597        }
3598        return null;
3599    }
3600
3601    @Override
3602    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3603        synchronized (mPackages) {
3604            return mServicesSystemSharedLibraryPackageName;
3605        }
3606    }
3607
3608    @Override
3609    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3610        synchronized (mPackages) {
3611            return mSharedSystemSharedLibraryPackageName;
3612        }
3613    }
3614
3615    @Override
3616    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3617        synchronized (mPackages) {
3618            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3619
3620            final FeatureInfo fi = new FeatureInfo();
3621            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3622                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3623            res.add(fi);
3624
3625            return new ParceledListSlice<>(res);
3626        }
3627    }
3628
3629    @Override
3630    public boolean hasSystemFeature(String name, int version) {
3631        synchronized (mPackages) {
3632            final FeatureInfo feat = mAvailableFeatures.get(name);
3633            if (feat == null) {
3634                return false;
3635            } else {
3636                return feat.version >= version;
3637            }
3638        }
3639    }
3640
3641    @Override
3642    public int checkPermission(String permName, String pkgName, int userId) {
3643        if (!sUserManager.exists(userId)) {
3644            return PackageManager.PERMISSION_DENIED;
3645        }
3646
3647        synchronized (mPackages) {
3648            final PackageParser.Package p = mPackages.get(pkgName);
3649            if (p != null && p.mExtras != null) {
3650                final PackageSetting ps = (PackageSetting) p.mExtras;
3651                final PermissionsState permissionsState = ps.getPermissionsState();
3652                if (permissionsState.hasPermission(permName, userId)) {
3653                    return PackageManager.PERMISSION_GRANTED;
3654                }
3655                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3656                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3657                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3658                    return PackageManager.PERMISSION_GRANTED;
3659                }
3660            }
3661        }
3662
3663        return PackageManager.PERMISSION_DENIED;
3664    }
3665
3666    @Override
3667    public int checkUidPermission(String permName, int uid) {
3668        final int userId = UserHandle.getUserId(uid);
3669
3670        if (!sUserManager.exists(userId)) {
3671            return PackageManager.PERMISSION_DENIED;
3672        }
3673
3674        synchronized (mPackages) {
3675            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3676            if (obj != null) {
3677                final SettingBase ps = (SettingBase) obj;
3678                final PermissionsState permissionsState = ps.getPermissionsState();
3679                if (permissionsState.hasPermission(permName, userId)) {
3680                    return PackageManager.PERMISSION_GRANTED;
3681                }
3682                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3683                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3684                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3685                    return PackageManager.PERMISSION_GRANTED;
3686                }
3687            } else {
3688                ArraySet<String> perms = mSystemPermissions.get(uid);
3689                if (perms != null) {
3690                    if (perms.contains(permName)) {
3691                        return PackageManager.PERMISSION_GRANTED;
3692                    }
3693                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3694                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3695                        return PackageManager.PERMISSION_GRANTED;
3696                    }
3697                }
3698            }
3699        }
3700
3701        return PackageManager.PERMISSION_DENIED;
3702    }
3703
3704    @Override
3705    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3706        if (UserHandle.getCallingUserId() != userId) {
3707            mContext.enforceCallingPermission(
3708                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3709                    "isPermissionRevokedByPolicy for user " + userId);
3710        }
3711
3712        if (checkPermission(permission, packageName, userId)
3713                == PackageManager.PERMISSION_GRANTED) {
3714            return false;
3715        }
3716
3717        final long identity = Binder.clearCallingIdentity();
3718        try {
3719            final int flags = getPermissionFlags(permission, packageName, userId);
3720            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3721        } finally {
3722            Binder.restoreCallingIdentity(identity);
3723        }
3724    }
3725
3726    @Override
3727    public String getPermissionControllerPackageName() {
3728        synchronized (mPackages) {
3729            return mRequiredInstallerPackage;
3730        }
3731    }
3732
3733    /**
3734     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3735     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3736     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3737     * @param message the message to log on security exception
3738     */
3739    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3740            boolean checkShell, String message) {
3741        if (userId < 0) {
3742            throw new IllegalArgumentException("Invalid userId " + userId);
3743        }
3744        if (checkShell) {
3745            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3746        }
3747        if (userId == UserHandle.getUserId(callingUid)) return;
3748        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3749            if (requireFullPermission) {
3750                mContext.enforceCallingOrSelfPermission(
3751                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3752            } else {
3753                try {
3754                    mContext.enforceCallingOrSelfPermission(
3755                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3756                } catch (SecurityException se) {
3757                    mContext.enforceCallingOrSelfPermission(
3758                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3759                }
3760            }
3761        }
3762    }
3763
3764    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3765        if (callingUid == Process.SHELL_UID) {
3766            if (userHandle >= 0
3767                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3768                throw new SecurityException("Shell does not have permission to access user "
3769                        + userHandle);
3770            } else if (userHandle < 0) {
3771                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3772                        + Debug.getCallers(3));
3773            }
3774        }
3775    }
3776
3777    private BasePermission findPermissionTreeLP(String permName) {
3778        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3779            if (permName.startsWith(bp.name) &&
3780                    permName.length() > bp.name.length() &&
3781                    permName.charAt(bp.name.length()) == '.') {
3782                return bp;
3783            }
3784        }
3785        return null;
3786    }
3787
3788    private BasePermission checkPermissionTreeLP(String permName) {
3789        if (permName != null) {
3790            BasePermission bp = findPermissionTreeLP(permName);
3791            if (bp != null) {
3792                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3793                    return bp;
3794                }
3795                throw new SecurityException("Calling uid "
3796                        + Binder.getCallingUid()
3797                        + " is not allowed to add to permission tree "
3798                        + bp.name + " owned by uid " + bp.uid);
3799            }
3800        }
3801        throw new SecurityException("No permission tree found for " + permName);
3802    }
3803
3804    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3805        if (s1 == null) {
3806            return s2 == null;
3807        }
3808        if (s2 == null) {
3809            return false;
3810        }
3811        if (s1.getClass() != s2.getClass()) {
3812            return false;
3813        }
3814        return s1.equals(s2);
3815    }
3816
3817    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3818        if (pi1.icon != pi2.icon) return false;
3819        if (pi1.logo != pi2.logo) return false;
3820        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3821        if (!compareStrings(pi1.name, pi2.name)) return false;
3822        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3823        // We'll take care of setting this one.
3824        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3825        // These are not currently stored in settings.
3826        //if (!compareStrings(pi1.group, pi2.group)) return false;
3827        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3828        //if (pi1.labelRes != pi2.labelRes) return false;
3829        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3830        return true;
3831    }
3832
3833    int permissionInfoFootprint(PermissionInfo info) {
3834        int size = info.name.length();
3835        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3836        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3837        return size;
3838    }
3839
3840    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3841        int size = 0;
3842        for (BasePermission perm : mSettings.mPermissions.values()) {
3843            if (perm.uid == tree.uid) {
3844                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3845            }
3846        }
3847        return size;
3848    }
3849
3850    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3851        // We calculate the max size of permissions defined by this uid and throw
3852        // if that plus the size of 'info' would exceed our stated maximum.
3853        if (tree.uid != Process.SYSTEM_UID) {
3854            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3855            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3856                throw new SecurityException("Permission tree size cap exceeded");
3857            }
3858        }
3859    }
3860
3861    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3862        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3863            throw new SecurityException("Label must be specified in permission");
3864        }
3865        BasePermission tree = checkPermissionTreeLP(info.name);
3866        BasePermission bp = mSettings.mPermissions.get(info.name);
3867        boolean added = bp == null;
3868        boolean changed = true;
3869        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3870        if (added) {
3871            enforcePermissionCapLocked(info, tree);
3872            bp = new BasePermission(info.name, tree.sourcePackage,
3873                    BasePermission.TYPE_DYNAMIC);
3874        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3875            throw new SecurityException(
3876                    "Not allowed to modify non-dynamic permission "
3877                    + info.name);
3878        } else {
3879            if (bp.protectionLevel == fixedLevel
3880                    && bp.perm.owner.equals(tree.perm.owner)
3881                    && bp.uid == tree.uid
3882                    && comparePermissionInfos(bp.perm.info, info)) {
3883                changed = false;
3884            }
3885        }
3886        bp.protectionLevel = fixedLevel;
3887        info = new PermissionInfo(info);
3888        info.protectionLevel = fixedLevel;
3889        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3890        bp.perm.info.packageName = tree.perm.info.packageName;
3891        bp.uid = tree.uid;
3892        if (added) {
3893            mSettings.mPermissions.put(info.name, bp);
3894        }
3895        if (changed) {
3896            if (!async) {
3897                mSettings.writeLPr();
3898            } else {
3899                scheduleWriteSettingsLocked();
3900            }
3901        }
3902        return added;
3903    }
3904
3905    @Override
3906    public boolean addPermission(PermissionInfo info) {
3907        synchronized (mPackages) {
3908            return addPermissionLocked(info, false);
3909        }
3910    }
3911
3912    @Override
3913    public boolean addPermissionAsync(PermissionInfo info) {
3914        synchronized (mPackages) {
3915            return addPermissionLocked(info, true);
3916        }
3917    }
3918
3919    @Override
3920    public void removePermission(String name) {
3921        synchronized (mPackages) {
3922            checkPermissionTreeLP(name);
3923            BasePermission bp = mSettings.mPermissions.get(name);
3924            if (bp != null) {
3925                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3926                    throw new SecurityException(
3927                            "Not allowed to modify non-dynamic permission "
3928                            + name);
3929                }
3930                mSettings.mPermissions.remove(name);
3931                mSettings.writeLPr();
3932            }
3933        }
3934    }
3935
3936    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3937            BasePermission bp) {
3938        int index = pkg.requestedPermissions.indexOf(bp.name);
3939        if (index == -1) {
3940            throw new SecurityException("Package " + pkg.packageName
3941                    + " has not requested permission " + bp.name);
3942        }
3943        if (!bp.isRuntime() && !bp.isDevelopment()) {
3944            throw new SecurityException("Permission " + bp.name
3945                    + " is not a changeable permission type");
3946        }
3947    }
3948
3949    @Override
3950    public void grantRuntimePermission(String packageName, String name, final int userId) {
3951        if (!sUserManager.exists(userId)) {
3952            Log.e(TAG, "No such user:" + userId);
3953            return;
3954        }
3955
3956        mContext.enforceCallingOrSelfPermission(
3957                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3958                "grantRuntimePermission");
3959
3960        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3961                true /* requireFullPermission */, true /* checkShell */,
3962                "grantRuntimePermission");
3963
3964        final int uid;
3965        final SettingBase sb;
3966
3967        synchronized (mPackages) {
3968            final PackageParser.Package pkg = mPackages.get(packageName);
3969            if (pkg == null) {
3970                throw new IllegalArgumentException("Unknown package: " + packageName);
3971            }
3972
3973            final BasePermission bp = mSettings.mPermissions.get(name);
3974            if (bp == null) {
3975                throw new IllegalArgumentException("Unknown permission: " + name);
3976            }
3977
3978            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3979
3980            // If a permission review is required for legacy apps we represent
3981            // their permissions as always granted runtime ones since we need
3982            // to keep the review required permission flag per user while an
3983            // install permission's state is shared across all users.
3984            if (Build.PERMISSIONS_REVIEW_REQUIRED
3985                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3986                    && bp.isRuntime()) {
3987                return;
3988            }
3989
3990            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3991            sb = (SettingBase) pkg.mExtras;
3992            if (sb == null) {
3993                throw new IllegalArgumentException("Unknown package: " + packageName);
3994            }
3995
3996            final PermissionsState permissionsState = sb.getPermissionsState();
3997
3998            final int flags = permissionsState.getPermissionFlags(name, userId);
3999            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4000                throw new SecurityException("Cannot grant system fixed permission "
4001                        + name + " for package " + packageName);
4002            }
4003
4004            if (bp.isDevelopment()) {
4005                // Development permissions must be handled specially, since they are not
4006                // normal runtime permissions.  For now they apply to all users.
4007                if (permissionsState.grantInstallPermission(bp) !=
4008                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4009                    scheduleWriteSettingsLocked();
4010                }
4011                return;
4012            }
4013
4014            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4015                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4016                return;
4017            }
4018
4019            final int result = permissionsState.grantRuntimePermission(bp, userId);
4020            switch (result) {
4021                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4022                    return;
4023                }
4024
4025                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4026                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4027                    mHandler.post(new Runnable() {
4028                        @Override
4029                        public void run() {
4030                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4031                        }
4032                    });
4033                }
4034                break;
4035            }
4036
4037            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4038
4039            // Not critical if that is lost - app has to request again.
4040            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4041        }
4042
4043        // Only need to do this if user is initialized. Otherwise it's a new user
4044        // and there are no processes running as the user yet and there's no need
4045        // to make an expensive call to remount processes for the changed permissions.
4046        if (READ_EXTERNAL_STORAGE.equals(name)
4047                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4048            final long token = Binder.clearCallingIdentity();
4049            try {
4050                if (sUserManager.isInitialized(userId)) {
4051                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4052                            MountServiceInternal.class);
4053                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4054                }
4055            } finally {
4056                Binder.restoreCallingIdentity(token);
4057            }
4058        }
4059    }
4060
4061    @Override
4062    public void revokeRuntimePermission(String packageName, String name, int userId) {
4063        if (!sUserManager.exists(userId)) {
4064            Log.e(TAG, "No such user:" + userId);
4065            return;
4066        }
4067
4068        mContext.enforceCallingOrSelfPermission(
4069                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4070                "revokeRuntimePermission");
4071
4072        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4073                true /* requireFullPermission */, true /* checkShell */,
4074                "revokeRuntimePermission");
4075
4076        final int appId;
4077
4078        synchronized (mPackages) {
4079            final PackageParser.Package pkg = mPackages.get(packageName);
4080            if (pkg == null) {
4081                throw new IllegalArgumentException("Unknown package: " + packageName);
4082            }
4083
4084            final BasePermission bp = mSettings.mPermissions.get(name);
4085            if (bp == null) {
4086                throw new IllegalArgumentException("Unknown permission: " + name);
4087            }
4088
4089            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4090
4091            // If a permission review is required for legacy apps we represent
4092            // their permissions as always granted runtime ones since we need
4093            // to keep the review required permission flag per user while an
4094            // install permission's state is shared across all users.
4095            if (Build.PERMISSIONS_REVIEW_REQUIRED
4096                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4097                    && bp.isRuntime()) {
4098                return;
4099            }
4100
4101            SettingBase sb = (SettingBase) pkg.mExtras;
4102            if (sb == null) {
4103                throw new IllegalArgumentException("Unknown package: " + packageName);
4104            }
4105
4106            final PermissionsState permissionsState = sb.getPermissionsState();
4107
4108            final int flags = permissionsState.getPermissionFlags(name, userId);
4109            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4110                throw new SecurityException("Cannot revoke system fixed permission "
4111                        + name + " for package " + packageName);
4112            }
4113
4114            if (bp.isDevelopment()) {
4115                // Development permissions must be handled specially, since they are not
4116                // normal runtime permissions.  For now they apply to all users.
4117                if (permissionsState.revokeInstallPermission(bp) !=
4118                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4119                    scheduleWriteSettingsLocked();
4120                }
4121                return;
4122            }
4123
4124            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4125                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4126                return;
4127            }
4128
4129            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4130
4131            // Critical, after this call app should never have the permission.
4132            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4133
4134            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4135        }
4136
4137        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4138    }
4139
4140    @Override
4141    public void resetRuntimePermissions() {
4142        mContext.enforceCallingOrSelfPermission(
4143                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4144                "revokeRuntimePermission");
4145
4146        int callingUid = Binder.getCallingUid();
4147        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4148            mContext.enforceCallingOrSelfPermission(
4149                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4150                    "resetRuntimePermissions");
4151        }
4152
4153        synchronized (mPackages) {
4154            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4155            for (int userId : UserManagerService.getInstance().getUserIds()) {
4156                final int packageCount = mPackages.size();
4157                for (int i = 0; i < packageCount; i++) {
4158                    PackageParser.Package pkg = mPackages.valueAt(i);
4159                    if (!(pkg.mExtras instanceof PackageSetting)) {
4160                        continue;
4161                    }
4162                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4163                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4164                }
4165            }
4166        }
4167    }
4168
4169    @Override
4170    public int getPermissionFlags(String name, String packageName, int userId) {
4171        if (!sUserManager.exists(userId)) {
4172            return 0;
4173        }
4174
4175        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4176
4177        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4178                true /* requireFullPermission */, false /* checkShell */,
4179                "getPermissionFlags");
4180
4181        synchronized (mPackages) {
4182            final PackageParser.Package pkg = mPackages.get(packageName);
4183            if (pkg == null) {
4184                return 0;
4185            }
4186
4187            final BasePermission bp = mSettings.mPermissions.get(name);
4188            if (bp == null) {
4189                return 0;
4190            }
4191
4192            SettingBase sb = (SettingBase) pkg.mExtras;
4193            if (sb == null) {
4194                return 0;
4195            }
4196
4197            PermissionsState permissionsState = sb.getPermissionsState();
4198            return permissionsState.getPermissionFlags(name, userId);
4199        }
4200    }
4201
4202    @Override
4203    public void updatePermissionFlags(String name, String packageName, int flagMask,
4204            int flagValues, int userId) {
4205        if (!sUserManager.exists(userId)) {
4206            return;
4207        }
4208
4209        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4210
4211        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4212                true /* requireFullPermission */, true /* checkShell */,
4213                "updatePermissionFlags");
4214
4215        // Only the system can change these flags and nothing else.
4216        if (getCallingUid() != Process.SYSTEM_UID) {
4217            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4218            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4219            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4220            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4221            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4222        }
4223
4224        synchronized (mPackages) {
4225            final PackageParser.Package pkg = mPackages.get(packageName);
4226            if (pkg == null) {
4227                throw new IllegalArgumentException("Unknown package: " + packageName);
4228            }
4229
4230            final BasePermission bp = mSettings.mPermissions.get(name);
4231            if (bp == null) {
4232                throw new IllegalArgumentException("Unknown permission: " + name);
4233            }
4234
4235            SettingBase sb = (SettingBase) pkg.mExtras;
4236            if (sb == null) {
4237                throw new IllegalArgumentException("Unknown package: " + packageName);
4238            }
4239
4240            PermissionsState permissionsState = sb.getPermissionsState();
4241
4242            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4243
4244            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4245                // Install and runtime permissions are stored in different places,
4246                // so figure out what permission changed and persist the change.
4247                if (permissionsState.getInstallPermissionState(name) != null) {
4248                    scheduleWriteSettingsLocked();
4249                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4250                        || hadState) {
4251                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4252                }
4253            }
4254        }
4255    }
4256
4257    /**
4258     * Update the permission flags for all packages and runtime permissions of a user in order
4259     * to allow device or profile owner to remove POLICY_FIXED.
4260     */
4261    @Override
4262    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4263        if (!sUserManager.exists(userId)) {
4264            return;
4265        }
4266
4267        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4268
4269        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4270                true /* requireFullPermission */, true /* checkShell */,
4271                "updatePermissionFlagsForAllApps");
4272
4273        // Only the system can change system fixed flags.
4274        if (getCallingUid() != Process.SYSTEM_UID) {
4275            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4276            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4277        }
4278
4279        synchronized (mPackages) {
4280            boolean changed = false;
4281            final int packageCount = mPackages.size();
4282            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4283                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4284                SettingBase sb = (SettingBase) pkg.mExtras;
4285                if (sb == null) {
4286                    continue;
4287                }
4288                PermissionsState permissionsState = sb.getPermissionsState();
4289                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4290                        userId, flagMask, flagValues);
4291            }
4292            if (changed) {
4293                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4294            }
4295        }
4296    }
4297
4298    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4299        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4300                != PackageManager.PERMISSION_GRANTED
4301            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4302                != PackageManager.PERMISSION_GRANTED) {
4303            throw new SecurityException(message + " requires "
4304                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4305                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4306        }
4307    }
4308
4309    @Override
4310    public boolean shouldShowRequestPermissionRationale(String permissionName,
4311            String packageName, int userId) {
4312        if (UserHandle.getCallingUserId() != userId) {
4313            mContext.enforceCallingPermission(
4314                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4315                    "canShowRequestPermissionRationale for user " + userId);
4316        }
4317
4318        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4319        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4320            return false;
4321        }
4322
4323        if (checkPermission(permissionName, packageName, userId)
4324                == PackageManager.PERMISSION_GRANTED) {
4325            return false;
4326        }
4327
4328        final int flags;
4329
4330        final long identity = Binder.clearCallingIdentity();
4331        try {
4332            flags = getPermissionFlags(permissionName,
4333                    packageName, userId);
4334        } finally {
4335            Binder.restoreCallingIdentity(identity);
4336        }
4337
4338        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4339                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4340                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4341
4342        if ((flags & fixedFlags) != 0) {
4343            return false;
4344        }
4345
4346        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4347    }
4348
4349    @Override
4350    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4351        mContext.enforceCallingOrSelfPermission(
4352                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4353                "addOnPermissionsChangeListener");
4354
4355        synchronized (mPackages) {
4356            mOnPermissionChangeListeners.addListenerLocked(listener);
4357        }
4358    }
4359
4360    @Override
4361    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4362        synchronized (mPackages) {
4363            mOnPermissionChangeListeners.removeListenerLocked(listener);
4364        }
4365    }
4366
4367    @Override
4368    public boolean isProtectedBroadcast(String actionName) {
4369        synchronized (mPackages) {
4370            if (mProtectedBroadcasts.contains(actionName)) {
4371                return true;
4372            } else if (actionName != null) {
4373                // TODO: remove these terrible hacks
4374                if (actionName.startsWith("android.net.netmon.lingerExpired")
4375                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4376                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4377                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4378                    return true;
4379                }
4380            }
4381        }
4382        return false;
4383    }
4384
4385    @Override
4386    public int checkSignatures(String pkg1, String pkg2) {
4387        synchronized (mPackages) {
4388            final PackageParser.Package p1 = mPackages.get(pkg1);
4389            final PackageParser.Package p2 = mPackages.get(pkg2);
4390            if (p1 == null || p1.mExtras == null
4391                    || p2 == null || p2.mExtras == null) {
4392                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4393            }
4394            return compareSignatures(p1.mSignatures, p2.mSignatures);
4395        }
4396    }
4397
4398    @Override
4399    public int checkUidSignatures(int uid1, int uid2) {
4400        // Map to base uids.
4401        uid1 = UserHandle.getAppId(uid1);
4402        uid2 = UserHandle.getAppId(uid2);
4403        // reader
4404        synchronized (mPackages) {
4405            Signature[] s1;
4406            Signature[] s2;
4407            Object obj = mSettings.getUserIdLPr(uid1);
4408            if (obj != null) {
4409                if (obj instanceof SharedUserSetting) {
4410                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4411                } else if (obj instanceof PackageSetting) {
4412                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4413                } else {
4414                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4415                }
4416            } else {
4417                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4418            }
4419            obj = mSettings.getUserIdLPr(uid2);
4420            if (obj != null) {
4421                if (obj instanceof SharedUserSetting) {
4422                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4423                } else if (obj instanceof PackageSetting) {
4424                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4425                } else {
4426                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4427                }
4428            } else {
4429                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4430            }
4431            return compareSignatures(s1, s2);
4432        }
4433    }
4434
4435    /**
4436     * This method should typically only be used when granting or revoking
4437     * permissions, since the app may immediately restart after this call.
4438     * <p>
4439     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4440     * guard your work against the app being relaunched.
4441     */
4442    private void killUid(int appId, int userId, String reason) {
4443        final long identity = Binder.clearCallingIdentity();
4444        try {
4445            IActivityManager am = ActivityManagerNative.getDefault();
4446            if (am != null) {
4447                try {
4448                    am.killUid(appId, userId, reason);
4449                } catch (RemoteException e) {
4450                    /* ignore - same process */
4451                }
4452            }
4453        } finally {
4454            Binder.restoreCallingIdentity(identity);
4455        }
4456    }
4457
4458    /**
4459     * Compares two sets of signatures. Returns:
4460     * <br />
4461     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4462     * <br />
4463     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4464     * <br />
4465     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4466     * <br />
4467     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4468     * <br />
4469     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4470     */
4471    static int compareSignatures(Signature[] s1, Signature[] s2) {
4472        if (s1 == null) {
4473            return s2 == null
4474                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4475                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4476        }
4477
4478        if (s2 == null) {
4479            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4480        }
4481
4482        if (s1.length != s2.length) {
4483            return PackageManager.SIGNATURE_NO_MATCH;
4484        }
4485
4486        // Since both signature sets are of size 1, we can compare without HashSets.
4487        if (s1.length == 1) {
4488            return s1[0].equals(s2[0]) ?
4489                    PackageManager.SIGNATURE_MATCH :
4490                    PackageManager.SIGNATURE_NO_MATCH;
4491        }
4492
4493        ArraySet<Signature> set1 = new ArraySet<Signature>();
4494        for (Signature sig : s1) {
4495            set1.add(sig);
4496        }
4497        ArraySet<Signature> set2 = new ArraySet<Signature>();
4498        for (Signature sig : s2) {
4499            set2.add(sig);
4500        }
4501        // Make sure s2 contains all signatures in s1.
4502        if (set1.equals(set2)) {
4503            return PackageManager.SIGNATURE_MATCH;
4504        }
4505        return PackageManager.SIGNATURE_NO_MATCH;
4506    }
4507
4508    /**
4509     * If the database version for this type of package (internal storage or
4510     * external storage) is less than the version where package signatures
4511     * were updated, return true.
4512     */
4513    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4514        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4515        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4516    }
4517
4518    /**
4519     * Used for backward compatibility to make sure any packages with
4520     * certificate chains get upgraded to the new style. {@code existingSigs}
4521     * will be in the old format (since they were stored on disk from before the
4522     * system upgrade) and {@code scannedSigs} will be in the newer format.
4523     */
4524    private int compareSignaturesCompat(PackageSignatures existingSigs,
4525            PackageParser.Package scannedPkg) {
4526        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4527            return PackageManager.SIGNATURE_NO_MATCH;
4528        }
4529
4530        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4531        for (Signature sig : existingSigs.mSignatures) {
4532            existingSet.add(sig);
4533        }
4534        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4535        for (Signature sig : scannedPkg.mSignatures) {
4536            try {
4537                Signature[] chainSignatures = sig.getChainSignatures();
4538                for (Signature chainSig : chainSignatures) {
4539                    scannedCompatSet.add(chainSig);
4540                }
4541            } catch (CertificateEncodingException e) {
4542                scannedCompatSet.add(sig);
4543            }
4544        }
4545        /*
4546         * Make sure the expanded scanned set contains all signatures in the
4547         * existing one.
4548         */
4549        if (scannedCompatSet.equals(existingSet)) {
4550            // Migrate the old signatures to the new scheme.
4551            existingSigs.assignSignatures(scannedPkg.mSignatures);
4552            // The new KeySets will be re-added later in the scanning process.
4553            synchronized (mPackages) {
4554                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4555            }
4556            return PackageManager.SIGNATURE_MATCH;
4557        }
4558        return PackageManager.SIGNATURE_NO_MATCH;
4559    }
4560
4561    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4562        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4563        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4564    }
4565
4566    private int compareSignaturesRecover(PackageSignatures existingSigs,
4567            PackageParser.Package scannedPkg) {
4568        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4569            return PackageManager.SIGNATURE_NO_MATCH;
4570        }
4571
4572        String msg = null;
4573        try {
4574            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4575                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4576                        + scannedPkg.packageName);
4577                return PackageManager.SIGNATURE_MATCH;
4578            }
4579        } catch (CertificateException e) {
4580            msg = e.getMessage();
4581        }
4582
4583        logCriticalInfo(Log.INFO,
4584                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4585        return PackageManager.SIGNATURE_NO_MATCH;
4586    }
4587
4588    @Override
4589    public List<String> getAllPackages() {
4590        synchronized (mPackages) {
4591            return new ArrayList<String>(mPackages.keySet());
4592        }
4593    }
4594
4595    @Override
4596    public String[] getPackagesForUid(int uid) {
4597        uid = UserHandle.getAppId(uid);
4598        // reader
4599        synchronized (mPackages) {
4600            Object obj = mSettings.getUserIdLPr(uid);
4601            if (obj instanceof SharedUserSetting) {
4602                final SharedUserSetting sus = (SharedUserSetting) obj;
4603                final int N = sus.packages.size();
4604                final String[] res = new String[N];
4605                for (int i = 0; i < N; i++) {
4606                    res[i] = sus.packages.valueAt(i).name;
4607                }
4608                return res;
4609            } else if (obj instanceof PackageSetting) {
4610                final PackageSetting ps = (PackageSetting) obj;
4611                return new String[] { ps.name };
4612            }
4613        }
4614        return null;
4615    }
4616
4617    @Override
4618    public String getNameForUid(int uid) {
4619        // reader
4620        synchronized (mPackages) {
4621            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4622            if (obj instanceof SharedUserSetting) {
4623                final SharedUserSetting sus = (SharedUserSetting) obj;
4624                return sus.name + ":" + sus.userId;
4625            } else if (obj instanceof PackageSetting) {
4626                final PackageSetting ps = (PackageSetting) obj;
4627                return ps.name;
4628            }
4629        }
4630        return null;
4631    }
4632
4633    @Override
4634    public int getUidForSharedUser(String sharedUserName) {
4635        if(sharedUserName == null) {
4636            return -1;
4637        }
4638        // reader
4639        synchronized (mPackages) {
4640            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4641            if (suid == null) {
4642                return -1;
4643            }
4644            return suid.userId;
4645        }
4646    }
4647
4648    @Override
4649    public int getFlagsForUid(int uid) {
4650        synchronized (mPackages) {
4651            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4652            if (obj instanceof SharedUserSetting) {
4653                final SharedUserSetting sus = (SharedUserSetting) obj;
4654                return sus.pkgFlags;
4655            } else if (obj instanceof PackageSetting) {
4656                final PackageSetting ps = (PackageSetting) obj;
4657                return ps.pkgFlags;
4658            }
4659        }
4660        return 0;
4661    }
4662
4663    @Override
4664    public int getPrivateFlagsForUid(int uid) {
4665        synchronized (mPackages) {
4666            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4667            if (obj instanceof SharedUserSetting) {
4668                final SharedUserSetting sus = (SharedUserSetting) obj;
4669                return sus.pkgPrivateFlags;
4670            } else if (obj instanceof PackageSetting) {
4671                final PackageSetting ps = (PackageSetting) obj;
4672                return ps.pkgPrivateFlags;
4673            }
4674        }
4675        return 0;
4676    }
4677
4678    @Override
4679    public boolean isUidPrivileged(int uid) {
4680        uid = UserHandle.getAppId(uid);
4681        // reader
4682        synchronized (mPackages) {
4683            Object obj = mSettings.getUserIdLPr(uid);
4684            if (obj instanceof SharedUserSetting) {
4685                final SharedUserSetting sus = (SharedUserSetting) obj;
4686                final Iterator<PackageSetting> it = sus.packages.iterator();
4687                while (it.hasNext()) {
4688                    if (it.next().isPrivileged()) {
4689                        return true;
4690                    }
4691                }
4692            } else if (obj instanceof PackageSetting) {
4693                final PackageSetting ps = (PackageSetting) obj;
4694                return ps.isPrivileged();
4695            }
4696        }
4697        return false;
4698    }
4699
4700    @Override
4701    public String[] getAppOpPermissionPackages(String permissionName) {
4702        synchronized (mPackages) {
4703            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4704            if (pkgs == null) {
4705                return null;
4706            }
4707            return pkgs.toArray(new String[pkgs.size()]);
4708        }
4709    }
4710
4711    @Override
4712    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4713            int flags, int userId) {
4714        try {
4715            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4716
4717            if (!sUserManager.exists(userId)) return null;
4718            flags = updateFlagsForResolve(flags, userId, intent);
4719            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4720                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4721
4722            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4723            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4724                    flags, userId);
4725            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4726
4727            final ResolveInfo bestChoice =
4728                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4729
4730            if (isEphemeralAllowed(intent, query, userId)) {
4731                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4732                final EphemeralResolveInfo ai =
4733                        getEphemeralResolveInfo(intent, resolvedType, userId);
4734                if (ai != null) {
4735                    if (DEBUG_EPHEMERAL) {
4736                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4737                    }
4738                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4739                    bestChoice.ephemeralResolveInfo = ai;
4740                }
4741                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4742            }
4743            return bestChoice;
4744        } finally {
4745            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4746        }
4747    }
4748
4749    @Override
4750    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4751            IntentFilter filter, int match, ComponentName activity) {
4752        final int userId = UserHandle.getCallingUserId();
4753        if (DEBUG_PREFERRED) {
4754            Log.v(TAG, "setLastChosenActivity intent=" + intent
4755                + " resolvedType=" + resolvedType
4756                + " flags=" + flags
4757                + " filter=" + filter
4758                + " match=" + match
4759                + " activity=" + activity);
4760            filter.dump(new PrintStreamPrinter(System.out), "    ");
4761        }
4762        intent.setComponent(null);
4763        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4764                userId);
4765        // Find any earlier preferred or last chosen entries and nuke them
4766        findPreferredActivity(intent, resolvedType,
4767                flags, query, 0, false, true, false, userId);
4768        // Add the new activity as the last chosen for this filter
4769        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4770                "Setting last chosen");
4771    }
4772
4773    @Override
4774    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4775        final int userId = UserHandle.getCallingUserId();
4776        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4777        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4778                userId);
4779        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4780                false, false, false, userId);
4781    }
4782
4783
4784    private boolean isEphemeralAllowed(
4785            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4786        // Short circuit and return early if possible.
4787        if (DISABLE_EPHEMERAL_APPS) {
4788            return false;
4789        }
4790        final int callingUser = UserHandle.getCallingUserId();
4791        if (callingUser != UserHandle.USER_SYSTEM) {
4792            return false;
4793        }
4794        if (mEphemeralResolverConnection == null) {
4795            return false;
4796        }
4797        if (intent.getComponent() != null) {
4798            return false;
4799        }
4800        if (intent.getPackage() != null) {
4801            return false;
4802        }
4803        final boolean isWebUri = hasWebURI(intent);
4804        if (!isWebUri) {
4805            return false;
4806        }
4807        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4808        synchronized (mPackages) {
4809            final int count = resolvedActivites.size();
4810            for (int n = 0; n < count; n++) {
4811                ResolveInfo info = resolvedActivites.get(n);
4812                String packageName = info.activityInfo.packageName;
4813                PackageSetting ps = mSettings.mPackages.get(packageName);
4814                if (ps != null) {
4815                    // Try to get the status from User settings first
4816                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4817                    int status = (int) (packedStatus >> 32);
4818                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4819                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4820                        if (DEBUG_EPHEMERAL) {
4821                            Slog.v(TAG, "DENY ephemeral apps;"
4822                                + " pkg: " + packageName + ", status: " + status);
4823                        }
4824                        return false;
4825                    }
4826                }
4827            }
4828        }
4829        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4830        return true;
4831    }
4832
4833    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4834            int userId) {
4835        final int ephemeralPrefixMask = Global.getInt(mContext.getContentResolver(),
4836                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4837        final int ephemeralPrefixCount = Global.getInt(mContext.getContentResolver(),
4838                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4839        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4840                ephemeralPrefixCount);
4841        final int[] shaPrefix = digest.getDigestPrefix();
4842        final byte[][] digestBytes = digest.getDigestBytes();
4843        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4844                mEphemeralResolverConnection.getEphemeralResolveInfoList(
4845                        shaPrefix, ephemeralPrefixMask);
4846        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4847            // No hash prefix match; there are no ephemeral apps for this domain.
4848            return null;
4849        }
4850
4851        // Go in reverse order so we match the narrowest scope first.
4852        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4853            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4854                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4855                    continue;
4856                }
4857                final List<IntentFilter> filters = ephemeralApplication.getFilters();
4858                // No filters; this should never happen.
4859                if (filters.isEmpty()) {
4860                    continue;
4861                }
4862                // We have a domain match; resolve the filters to see if anything matches.
4863                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4864                for (int j = filters.size() - 1; j >= 0; --j) {
4865                    final EphemeralResolveIntentInfo intentInfo =
4866                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4867                    ephemeralResolver.addFilter(intentInfo);
4868                }
4869                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4870                        intent, resolvedType, false /*defaultOnly*/, userId);
4871                if (!matchedResolveInfoList.isEmpty()) {
4872                    return matchedResolveInfoList.get(0);
4873                }
4874            }
4875        }
4876        // Hash or filter mis-match; no ephemeral apps for this domain.
4877        return null;
4878    }
4879
4880    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4881            int flags, List<ResolveInfo> query, int userId) {
4882        if (query != null) {
4883            final int N = query.size();
4884            if (N == 1) {
4885                return query.get(0);
4886            } else if (N > 1) {
4887                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4888                // If there is more than one activity with the same priority,
4889                // then let the user decide between them.
4890                ResolveInfo r0 = query.get(0);
4891                ResolveInfo r1 = query.get(1);
4892                if (DEBUG_INTENT_MATCHING || debug) {
4893                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4894                            + r1.activityInfo.name + "=" + r1.priority);
4895                }
4896                // If the first activity has a higher priority, or a different
4897                // default, then it is always desirable to pick it.
4898                if (r0.priority != r1.priority
4899                        || r0.preferredOrder != r1.preferredOrder
4900                        || r0.isDefault != r1.isDefault) {
4901                    return query.get(0);
4902                }
4903                // If we have saved a preference for a preferred activity for
4904                // this Intent, use that.
4905                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4906                        flags, query, r0.priority, true, false, debug, userId);
4907                if (ri != null) {
4908                    return ri;
4909                }
4910                ri = new ResolveInfo(mResolveInfo);
4911                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4912                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
4913                // If all of the options come from the same package, show the application's
4914                // label and icon instead of the generic resolver's.
4915                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
4916                // and then throw away the ResolveInfo itself, meaning that the caller loses
4917                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
4918                // a fallback for this case; we only set the target package's resources on
4919                // the ResolveInfo, not the ActivityInfo.
4920                final String intentPackage = intent.getPackage();
4921                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
4922                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
4923                    ri.resolvePackageName = intentPackage;
4924                    if (userNeedsBadging(userId)) {
4925                        ri.noResourceId = true;
4926                    } else {
4927                        ri.icon = appi.icon;
4928                    }
4929                    ri.iconResourceId = appi.icon;
4930                    ri.labelRes = appi.labelRes;
4931                }
4932                ri.activityInfo.applicationInfo = new ApplicationInfo(
4933                        ri.activityInfo.applicationInfo);
4934                if (userId != 0) {
4935                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4936                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4937                }
4938                // Make sure that the resolver is displayable in car mode
4939                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4940                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4941                return ri;
4942            }
4943        }
4944        return null;
4945    }
4946
4947    /**
4948     * Return true if the given list is not empty and all of its contents have
4949     * an activityInfo with the given package name.
4950     */
4951    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
4952        if (ArrayUtils.isEmpty(list)) {
4953            return false;
4954        }
4955        for (int i = 0, N = list.size(); i < N; i++) {
4956            final ResolveInfo ri = list.get(i);
4957            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
4958            if (ai == null || !packageName.equals(ai.packageName)) {
4959                return false;
4960            }
4961        }
4962        return true;
4963    }
4964
4965    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4966            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4967        final int N = query.size();
4968        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4969                .get(userId);
4970        // Get the list of persistent preferred activities that handle the intent
4971        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4972        List<PersistentPreferredActivity> pprefs = ppir != null
4973                ? ppir.queryIntent(intent, resolvedType,
4974                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4975                : null;
4976        if (pprefs != null && pprefs.size() > 0) {
4977            final int M = pprefs.size();
4978            for (int i=0; i<M; i++) {
4979                final PersistentPreferredActivity ppa = pprefs.get(i);
4980                if (DEBUG_PREFERRED || debug) {
4981                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4982                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4983                            + "\n  component=" + ppa.mComponent);
4984                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4985                }
4986                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4987                        flags | MATCH_DISABLED_COMPONENTS, userId);
4988                if (DEBUG_PREFERRED || debug) {
4989                    Slog.v(TAG, "Found persistent preferred activity:");
4990                    if (ai != null) {
4991                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4992                    } else {
4993                        Slog.v(TAG, "  null");
4994                    }
4995                }
4996                if (ai == null) {
4997                    // This previously registered persistent preferred activity
4998                    // component is no longer known. Ignore it and do NOT remove it.
4999                    continue;
5000                }
5001                for (int j=0; j<N; j++) {
5002                    final ResolveInfo ri = query.get(j);
5003                    if (!ri.activityInfo.applicationInfo.packageName
5004                            .equals(ai.applicationInfo.packageName)) {
5005                        continue;
5006                    }
5007                    if (!ri.activityInfo.name.equals(ai.name)) {
5008                        continue;
5009                    }
5010                    //  Found a persistent preference that can handle the intent.
5011                    if (DEBUG_PREFERRED || debug) {
5012                        Slog.v(TAG, "Returning persistent preferred activity: " +
5013                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5014                    }
5015                    return ri;
5016                }
5017            }
5018        }
5019        return null;
5020    }
5021
5022    // TODO: handle preferred activities missing while user has amnesia
5023    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5024            List<ResolveInfo> query, int priority, boolean always,
5025            boolean removeMatches, boolean debug, int userId) {
5026        if (!sUserManager.exists(userId)) return null;
5027        flags = updateFlagsForResolve(flags, userId, intent);
5028        // writer
5029        synchronized (mPackages) {
5030            if (intent.getSelector() != null) {
5031                intent = intent.getSelector();
5032            }
5033            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5034
5035            // Try to find a matching persistent preferred activity.
5036            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5037                    debug, userId);
5038
5039            // If a persistent preferred activity matched, use it.
5040            if (pri != null) {
5041                return pri;
5042            }
5043
5044            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5045            // Get the list of preferred activities that handle the intent
5046            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5047            List<PreferredActivity> prefs = pir != null
5048                    ? pir.queryIntent(intent, resolvedType,
5049                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5050                    : null;
5051            if (prefs != null && prefs.size() > 0) {
5052                boolean changed = false;
5053                try {
5054                    // First figure out how good the original match set is.
5055                    // We will only allow preferred activities that came
5056                    // from the same match quality.
5057                    int match = 0;
5058
5059                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5060
5061                    final int N = query.size();
5062                    for (int j=0; j<N; j++) {
5063                        final ResolveInfo ri = query.get(j);
5064                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5065                                + ": 0x" + Integer.toHexString(match));
5066                        if (ri.match > match) {
5067                            match = ri.match;
5068                        }
5069                    }
5070
5071                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5072                            + Integer.toHexString(match));
5073
5074                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5075                    final int M = prefs.size();
5076                    for (int i=0; i<M; i++) {
5077                        final PreferredActivity pa = prefs.get(i);
5078                        if (DEBUG_PREFERRED || debug) {
5079                            Slog.v(TAG, "Checking PreferredActivity ds="
5080                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5081                                    + "\n  component=" + pa.mPref.mComponent);
5082                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5083                        }
5084                        if (pa.mPref.mMatch != match) {
5085                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5086                                    + Integer.toHexString(pa.mPref.mMatch));
5087                            continue;
5088                        }
5089                        // If it's not an "always" type preferred activity and that's what we're
5090                        // looking for, skip it.
5091                        if (always && !pa.mPref.mAlways) {
5092                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5093                            continue;
5094                        }
5095                        final ActivityInfo ai = getActivityInfo(
5096                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5097                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5098                                userId);
5099                        if (DEBUG_PREFERRED || debug) {
5100                            Slog.v(TAG, "Found preferred activity:");
5101                            if (ai != null) {
5102                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5103                            } else {
5104                                Slog.v(TAG, "  null");
5105                            }
5106                        }
5107                        if (ai == null) {
5108                            // This previously registered preferred activity
5109                            // component is no longer known.  Most likely an update
5110                            // to the app was installed and in the new version this
5111                            // component no longer exists.  Clean it up by removing
5112                            // it from the preferred activities list, and skip it.
5113                            Slog.w(TAG, "Removing dangling preferred activity: "
5114                                    + pa.mPref.mComponent);
5115                            pir.removeFilter(pa);
5116                            changed = true;
5117                            continue;
5118                        }
5119                        for (int j=0; j<N; j++) {
5120                            final ResolveInfo ri = query.get(j);
5121                            if (!ri.activityInfo.applicationInfo.packageName
5122                                    .equals(ai.applicationInfo.packageName)) {
5123                                continue;
5124                            }
5125                            if (!ri.activityInfo.name.equals(ai.name)) {
5126                                continue;
5127                            }
5128
5129                            if (removeMatches) {
5130                                pir.removeFilter(pa);
5131                                changed = true;
5132                                if (DEBUG_PREFERRED) {
5133                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5134                                }
5135                                break;
5136                            }
5137
5138                            // Okay we found a previously set preferred or last chosen app.
5139                            // If the result set is different from when this
5140                            // was created, we need to clear it and re-ask the
5141                            // user their preference, if we're looking for an "always" type entry.
5142                            if (always && !pa.mPref.sameSet(query)) {
5143                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5144                                        + intent + " type " + resolvedType);
5145                                if (DEBUG_PREFERRED) {
5146                                    Slog.v(TAG, "Removing preferred activity since set changed "
5147                                            + pa.mPref.mComponent);
5148                                }
5149                                pir.removeFilter(pa);
5150                                // Re-add the filter as a "last chosen" entry (!always)
5151                                PreferredActivity lastChosen = new PreferredActivity(
5152                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5153                                pir.addFilter(lastChosen);
5154                                changed = true;
5155                                return null;
5156                            }
5157
5158                            // Yay! Either the set matched or we're looking for the last chosen
5159                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5160                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5161                            return ri;
5162                        }
5163                    }
5164                } finally {
5165                    if (changed) {
5166                        if (DEBUG_PREFERRED) {
5167                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5168                        }
5169                        scheduleWritePackageRestrictionsLocked(userId);
5170                    }
5171                }
5172            }
5173        }
5174        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5175        return null;
5176    }
5177
5178    /*
5179     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5180     */
5181    @Override
5182    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5183            int targetUserId) {
5184        mContext.enforceCallingOrSelfPermission(
5185                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5186        List<CrossProfileIntentFilter> matches =
5187                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5188        if (matches != null) {
5189            int size = matches.size();
5190            for (int i = 0; i < size; i++) {
5191                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5192            }
5193        }
5194        if (hasWebURI(intent)) {
5195            // cross-profile app linking works only towards the parent.
5196            final UserInfo parent = getProfileParent(sourceUserId);
5197            synchronized(mPackages) {
5198                int flags = updateFlagsForResolve(0, parent.id, intent);
5199                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5200                        intent, resolvedType, flags, sourceUserId, parent.id);
5201                return xpDomainInfo != null;
5202            }
5203        }
5204        return false;
5205    }
5206
5207    private UserInfo getProfileParent(int userId) {
5208        final long identity = Binder.clearCallingIdentity();
5209        try {
5210            return sUserManager.getProfileParent(userId);
5211        } finally {
5212            Binder.restoreCallingIdentity(identity);
5213        }
5214    }
5215
5216    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5217            String resolvedType, int userId) {
5218        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5219        if (resolver != null) {
5220            return resolver.queryIntent(intent, resolvedType, false, userId);
5221        }
5222        return null;
5223    }
5224
5225    @Override
5226    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5227            String resolvedType, int flags, int userId) {
5228        try {
5229            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5230
5231            return new ParceledListSlice<>(
5232                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5233        } finally {
5234            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5235        }
5236    }
5237
5238    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5239            String resolvedType, int flags, int userId) {
5240        if (!sUserManager.exists(userId)) return Collections.emptyList();
5241        flags = updateFlagsForResolve(flags, userId, intent);
5242        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5243                false /* requireFullPermission */, false /* checkShell */,
5244                "query intent activities");
5245        ComponentName comp = intent.getComponent();
5246        if (comp == null) {
5247            if (intent.getSelector() != null) {
5248                intent = intent.getSelector();
5249                comp = intent.getComponent();
5250            }
5251        }
5252
5253        if (comp != null) {
5254            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5255            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5256            if (ai != null) {
5257                final ResolveInfo ri = new ResolveInfo();
5258                ri.activityInfo = ai;
5259                list.add(ri);
5260            }
5261            return list;
5262        }
5263
5264        // reader
5265        synchronized (mPackages) {
5266            final String pkgName = intent.getPackage();
5267            if (pkgName == null) {
5268                List<CrossProfileIntentFilter> matchingFilters =
5269                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5270                // Check for results that need to skip the current profile.
5271                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5272                        resolvedType, flags, userId);
5273                if (xpResolveInfo != null) {
5274                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5275                    result.add(xpResolveInfo);
5276                    return filterIfNotSystemUser(result, userId);
5277                }
5278
5279                // Check for results in the current profile.
5280                List<ResolveInfo> result = mActivities.queryIntent(
5281                        intent, resolvedType, flags, userId);
5282                result = filterIfNotSystemUser(result, userId);
5283
5284                // Check for cross profile results.
5285                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5286                xpResolveInfo = queryCrossProfileIntents(
5287                        matchingFilters, intent, resolvedType, flags, userId,
5288                        hasNonNegativePriorityResult);
5289                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5290                    boolean isVisibleToUser = filterIfNotSystemUser(
5291                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5292                    if (isVisibleToUser) {
5293                        result.add(xpResolveInfo);
5294                        Collections.sort(result, mResolvePrioritySorter);
5295                    }
5296                }
5297                if (hasWebURI(intent)) {
5298                    CrossProfileDomainInfo xpDomainInfo = null;
5299                    final UserInfo parent = getProfileParent(userId);
5300                    if (parent != null) {
5301                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5302                                flags, userId, parent.id);
5303                    }
5304                    if (xpDomainInfo != null) {
5305                        if (xpResolveInfo != null) {
5306                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5307                            // in the result.
5308                            result.remove(xpResolveInfo);
5309                        }
5310                        if (result.size() == 0) {
5311                            result.add(xpDomainInfo.resolveInfo);
5312                            return result;
5313                        }
5314                    } else if (result.size() <= 1) {
5315                        return result;
5316                    }
5317                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5318                            xpDomainInfo, userId);
5319                    Collections.sort(result, mResolvePrioritySorter);
5320                }
5321                return result;
5322            }
5323            final PackageParser.Package pkg = mPackages.get(pkgName);
5324            if (pkg != null) {
5325                return filterIfNotSystemUser(
5326                        mActivities.queryIntentForPackage(
5327                                intent, resolvedType, flags, pkg.activities, userId),
5328                        userId);
5329            }
5330            return new ArrayList<ResolveInfo>();
5331        }
5332    }
5333
5334    private static class CrossProfileDomainInfo {
5335        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5336        ResolveInfo resolveInfo;
5337        /* Best domain verification status of the activities found in the other profile */
5338        int bestDomainVerificationStatus;
5339    }
5340
5341    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5342            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5343        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5344                sourceUserId)) {
5345            return null;
5346        }
5347        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5348                resolvedType, flags, parentUserId);
5349
5350        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5351            return null;
5352        }
5353        CrossProfileDomainInfo result = null;
5354        int size = resultTargetUser.size();
5355        for (int i = 0; i < size; i++) {
5356            ResolveInfo riTargetUser = resultTargetUser.get(i);
5357            // Intent filter verification is only for filters that specify a host. So don't return
5358            // those that handle all web uris.
5359            if (riTargetUser.handleAllWebDataURI) {
5360                continue;
5361            }
5362            String packageName = riTargetUser.activityInfo.packageName;
5363            PackageSetting ps = mSettings.mPackages.get(packageName);
5364            if (ps == null) {
5365                continue;
5366            }
5367            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5368            int status = (int)(verificationState >> 32);
5369            if (result == null) {
5370                result = new CrossProfileDomainInfo();
5371                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5372                        sourceUserId, parentUserId);
5373                result.bestDomainVerificationStatus = status;
5374            } else {
5375                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5376                        result.bestDomainVerificationStatus);
5377            }
5378        }
5379        // Don't consider matches with status NEVER across profiles.
5380        if (result != null && result.bestDomainVerificationStatus
5381                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5382            return null;
5383        }
5384        return result;
5385    }
5386
5387    /**
5388     * Verification statuses are ordered from the worse to the best, except for
5389     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5390     */
5391    private int bestDomainVerificationStatus(int status1, int status2) {
5392        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5393            return status2;
5394        }
5395        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5396            return status1;
5397        }
5398        return (int) MathUtils.max(status1, status2);
5399    }
5400
5401    private boolean isUserEnabled(int userId) {
5402        long callingId = Binder.clearCallingIdentity();
5403        try {
5404            UserInfo userInfo = sUserManager.getUserInfo(userId);
5405            return userInfo != null && userInfo.isEnabled();
5406        } finally {
5407            Binder.restoreCallingIdentity(callingId);
5408        }
5409    }
5410
5411    /**
5412     * Filter out activities with systemUserOnly flag set, when current user is not System.
5413     *
5414     * @return filtered list
5415     */
5416    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5417        if (userId == UserHandle.USER_SYSTEM) {
5418            return resolveInfos;
5419        }
5420        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5421            ResolveInfo info = resolveInfos.get(i);
5422            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5423                resolveInfos.remove(i);
5424            }
5425        }
5426        return resolveInfos;
5427    }
5428
5429    /**
5430     * @param resolveInfos list of resolve infos in descending priority order
5431     * @return if the list contains a resolve info with non-negative priority
5432     */
5433    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5434        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5435    }
5436
5437    private static boolean hasWebURI(Intent intent) {
5438        if (intent.getData() == null) {
5439            return false;
5440        }
5441        final String scheme = intent.getScheme();
5442        if (TextUtils.isEmpty(scheme)) {
5443            return false;
5444        }
5445        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5446    }
5447
5448    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5449            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5450            int userId) {
5451        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5452
5453        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5454            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5455                    candidates.size());
5456        }
5457
5458        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5459        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5460        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5461        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5462        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5463        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5464
5465        synchronized (mPackages) {
5466            final int count = candidates.size();
5467            // First, try to use linked apps. Partition the candidates into four lists:
5468            // one for the final results, one for the "do not use ever", one for "undefined status"
5469            // and finally one for "browser app type".
5470            for (int n=0; n<count; n++) {
5471                ResolveInfo info = candidates.get(n);
5472                String packageName = info.activityInfo.packageName;
5473                PackageSetting ps = mSettings.mPackages.get(packageName);
5474                if (ps != null) {
5475                    // Add to the special match all list (Browser use case)
5476                    if (info.handleAllWebDataURI) {
5477                        matchAllList.add(info);
5478                        continue;
5479                    }
5480                    // Try to get the status from User settings first
5481                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5482                    int status = (int)(packedStatus >> 32);
5483                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5484                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5485                        if (DEBUG_DOMAIN_VERIFICATION) {
5486                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5487                                    + " : linkgen=" + linkGeneration);
5488                        }
5489                        // Use link-enabled generation as preferredOrder, i.e.
5490                        // prefer newly-enabled over earlier-enabled.
5491                        info.preferredOrder = linkGeneration;
5492                        alwaysList.add(info);
5493                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5494                        if (DEBUG_DOMAIN_VERIFICATION) {
5495                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5496                        }
5497                        neverList.add(info);
5498                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5499                        if (DEBUG_DOMAIN_VERIFICATION) {
5500                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5501                        }
5502                        alwaysAskList.add(info);
5503                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5504                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5505                        if (DEBUG_DOMAIN_VERIFICATION) {
5506                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5507                        }
5508                        undefinedList.add(info);
5509                    }
5510                }
5511            }
5512
5513            // We'll want to include browser possibilities in a few cases
5514            boolean includeBrowser = false;
5515
5516            // First try to add the "always" resolution(s) for the current user, if any
5517            if (alwaysList.size() > 0) {
5518                result.addAll(alwaysList);
5519            } else {
5520                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5521                result.addAll(undefinedList);
5522                // Maybe add one for the other profile.
5523                if (xpDomainInfo != null && (
5524                        xpDomainInfo.bestDomainVerificationStatus
5525                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5526                    result.add(xpDomainInfo.resolveInfo);
5527                }
5528                includeBrowser = true;
5529            }
5530
5531            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5532            // If there were 'always' entries their preferred order has been set, so we also
5533            // back that off to make the alternatives equivalent
5534            if (alwaysAskList.size() > 0) {
5535                for (ResolveInfo i : result) {
5536                    i.preferredOrder = 0;
5537                }
5538                result.addAll(alwaysAskList);
5539                includeBrowser = true;
5540            }
5541
5542            if (includeBrowser) {
5543                // Also add browsers (all of them or only the default one)
5544                if (DEBUG_DOMAIN_VERIFICATION) {
5545                    Slog.v(TAG, "   ...including browsers in candidate set");
5546                }
5547                if ((matchFlags & MATCH_ALL) != 0) {
5548                    result.addAll(matchAllList);
5549                } else {
5550                    // Browser/generic handling case.  If there's a default browser, go straight
5551                    // to that (but only if there is no other higher-priority match).
5552                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5553                    int maxMatchPrio = 0;
5554                    ResolveInfo defaultBrowserMatch = null;
5555                    final int numCandidates = matchAllList.size();
5556                    for (int n = 0; n < numCandidates; n++) {
5557                        ResolveInfo info = matchAllList.get(n);
5558                        // track the highest overall match priority...
5559                        if (info.priority > maxMatchPrio) {
5560                            maxMatchPrio = info.priority;
5561                        }
5562                        // ...and the highest-priority default browser match
5563                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5564                            if (defaultBrowserMatch == null
5565                                    || (defaultBrowserMatch.priority < info.priority)) {
5566                                if (debug) {
5567                                    Slog.v(TAG, "Considering default browser match " + info);
5568                                }
5569                                defaultBrowserMatch = info;
5570                            }
5571                        }
5572                    }
5573                    if (defaultBrowserMatch != null
5574                            && defaultBrowserMatch.priority >= maxMatchPrio
5575                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5576                    {
5577                        if (debug) {
5578                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5579                        }
5580                        result.add(defaultBrowserMatch);
5581                    } else {
5582                        result.addAll(matchAllList);
5583                    }
5584                }
5585
5586                // If there is nothing selected, add all candidates and remove the ones that the user
5587                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5588                if (result.size() == 0) {
5589                    result.addAll(candidates);
5590                    result.removeAll(neverList);
5591                }
5592            }
5593        }
5594        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5595            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5596                    result.size());
5597            for (ResolveInfo info : result) {
5598                Slog.v(TAG, "  + " + info.activityInfo);
5599            }
5600        }
5601        return result;
5602    }
5603
5604    // Returns a packed value as a long:
5605    //
5606    // high 'int'-sized word: link status: undefined/ask/never/always.
5607    // low 'int'-sized word: relative priority among 'always' results.
5608    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5609        long result = ps.getDomainVerificationStatusForUser(userId);
5610        // if none available, get the master status
5611        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5612            if (ps.getIntentFilterVerificationInfo() != null) {
5613                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5614            }
5615        }
5616        return result;
5617    }
5618
5619    private ResolveInfo querySkipCurrentProfileIntents(
5620            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5621            int flags, int sourceUserId) {
5622        if (matchingFilters != null) {
5623            int size = matchingFilters.size();
5624            for (int i = 0; i < size; i ++) {
5625                CrossProfileIntentFilter filter = matchingFilters.get(i);
5626                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5627                    // Checking if there are activities in the target user that can handle the
5628                    // intent.
5629                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5630                            resolvedType, flags, sourceUserId);
5631                    if (resolveInfo != null) {
5632                        return resolveInfo;
5633                    }
5634                }
5635            }
5636        }
5637        return null;
5638    }
5639
5640    // Return matching ResolveInfo in target user if any.
5641    private ResolveInfo queryCrossProfileIntents(
5642            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5643            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5644        if (matchingFilters != null) {
5645            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5646            // match the same intent. For performance reasons, it is better not to
5647            // run queryIntent twice for the same userId
5648            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5649            int size = matchingFilters.size();
5650            for (int i = 0; i < size; i++) {
5651                CrossProfileIntentFilter filter = matchingFilters.get(i);
5652                int targetUserId = filter.getTargetUserId();
5653                boolean skipCurrentProfile =
5654                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5655                boolean skipCurrentProfileIfNoMatchFound =
5656                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5657                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5658                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5659                    // Checking if there are activities in the target user that can handle the
5660                    // intent.
5661                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5662                            resolvedType, flags, sourceUserId);
5663                    if (resolveInfo != null) return resolveInfo;
5664                    alreadyTriedUserIds.put(targetUserId, true);
5665                }
5666            }
5667        }
5668        return null;
5669    }
5670
5671    /**
5672     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5673     * will forward the intent to the filter's target user.
5674     * Otherwise, returns null.
5675     */
5676    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5677            String resolvedType, int flags, int sourceUserId) {
5678        int targetUserId = filter.getTargetUserId();
5679        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5680                resolvedType, flags, targetUserId);
5681        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5682            // If all the matches in the target profile are suspended, return null.
5683            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5684                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5685                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5686                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5687                            targetUserId);
5688                }
5689            }
5690        }
5691        return null;
5692    }
5693
5694    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5695            int sourceUserId, int targetUserId) {
5696        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5697        long ident = Binder.clearCallingIdentity();
5698        boolean targetIsProfile;
5699        try {
5700            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5701        } finally {
5702            Binder.restoreCallingIdentity(ident);
5703        }
5704        String className;
5705        if (targetIsProfile) {
5706            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5707        } else {
5708            className = FORWARD_INTENT_TO_PARENT;
5709        }
5710        ComponentName forwardingActivityComponentName = new ComponentName(
5711                mAndroidApplication.packageName, className);
5712        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5713                sourceUserId);
5714        if (!targetIsProfile) {
5715            forwardingActivityInfo.showUserIcon = targetUserId;
5716            forwardingResolveInfo.noResourceId = true;
5717        }
5718        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5719        forwardingResolveInfo.priority = 0;
5720        forwardingResolveInfo.preferredOrder = 0;
5721        forwardingResolveInfo.match = 0;
5722        forwardingResolveInfo.isDefault = true;
5723        forwardingResolveInfo.filter = filter;
5724        forwardingResolveInfo.targetUserId = targetUserId;
5725        return forwardingResolveInfo;
5726    }
5727
5728    @Override
5729    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5730            Intent[] specifics, String[] specificTypes, Intent intent,
5731            String resolvedType, int flags, int userId) {
5732        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5733                specificTypes, intent, resolvedType, flags, userId));
5734    }
5735
5736    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5737            Intent[] specifics, String[] specificTypes, Intent intent,
5738            String resolvedType, int flags, int userId) {
5739        if (!sUserManager.exists(userId)) return Collections.emptyList();
5740        flags = updateFlagsForResolve(flags, userId, intent);
5741        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5742                false /* requireFullPermission */, false /* checkShell */,
5743                "query intent activity options");
5744        final String resultsAction = intent.getAction();
5745
5746        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5747                | PackageManager.GET_RESOLVED_FILTER, userId);
5748
5749        if (DEBUG_INTENT_MATCHING) {
5750            Log.v(TAG, "Query " + intent + ": " + results);
5751        }
5752
5753        int specificsPos = 0;
5754        int N;
5755
5756        // todo: note that the algorithm used here is O(N^2).  This
5757        // isn't a problem in our current environment, but if we start running
5758        // into situations where we have more than 5 or 10 matches then this
5759        // should probably be changed to something smarter...
5760
5761        // First we go through and resolve each of the specific items
5762        // that were supplied, taking care of removing any corresponding
5763        // duplicate items in the generic resolve list.
5764        if (specifics != null) {
5765            for (int i=0; i<specifics.length; i++) {
5766                final Intent sintent = specifics[i];
5767                if (sintent == null) {
5768                    continue;
5769                }
5770
5771                if (DEBUG_INTENT_MATCHING) {
5772                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5773                }
5774
5775                String action = sintent.getAction();
5776                if (resultsAction != null && resultsAction.equals(action)) {
5777                    // If this action was explicitly requested, then don't
5778                    // remove things that have it.
5779                    action = null;
5780                }
5781
5782                ResolveInfo ri = null;
5783                ActivityInfo ai = null;
5784
5785                ComponentName comp = sintent.getComponent();
5786                if (comp == null) {
5787                    ri = resolveIntent(
5788                        sintent,
5789                        specificTypes != null ? specificTypes[i] : null,
5790                            flags, userId);
5791                    if (ri == null) {
5792                        continue;
5793                    }
5794                    if (ri == mResolveInfo) {
5795                        // ACK!  Must do something better with this.
5796                    }
5797                    ai = ri.activityInfo;
5798                    comp = new ComponentName(ai.applicationInfo.packageName,
5799                            ai.name);
5800                } else {
5801                    ai = getActivityInfo(comp, flags, userId);
5802                    if (ai == null) {
5803                        continue;
5804                    }
5805                }
5806
5807                // Look for any generic query activities that are duplicates
5808                // of this specific one, and remove them from the results.
5809                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5810                N = results.size();
5811                int j;
5812                for (j=specificsPos; j<N; j++) {
5813                    ResolveInfo sri = results.get(j);
5814                    if ((sri.activityInfo.name.equals(comp.getClassName())
5815                            && sri.activityInfo.applicationInfo.packageName.equals(
5816                                    comp.getPackageName()))
5817                        || (action != null && sri.filter.matchAction(action))) {
5818                        results.remove(j);
5819                        if (DEBUG_INTENT_MATCHING) Log.v(
5820                            TAG, "Removing duplicate item from " + j
5821                            + " due to specific " + specificsPos);
5822                        if (ri == null) {
5823                            ri = sri;
5824                        }
5825                        j--;
5826                        N--;
5827                    }
5828                }
5829
5830                // Add this specific item to its proper place.
5831                if (ri == null) {
5832                    ri = new ResolveInfo();
5833                    ri.activityInfo = ai;
5834                }
5835                results.add(specificsPos, ri);
5836                ri.specificIndex = i;
5837                specificsPos++;
5838            }
5839        }
5840
5841        // Now we go through the remaining generic results and remove any
5842        // duplicate actions that are found here.
5843        N = results.size();
5844        for (int i=specificsPos; i<N-1; i++) {
5845            final ResolveInfo rii = results.get(i);
5846            if (rii.filter == null) {
5847                continue;
5848            }
5849
5850            // Iterate over all of the actions of this result's intent
5851            // filter...  typically this should be just one.
5852            final Iterator<String> it = rii.filter.actionsIterator();
5853            if (it == null) {
5854                continue;
5855            }
5856            while (it.hasNext()) {
5857                final String action = it.next();
5858                if (resultsAction != null && resultsAction.equals(action)) {
5859                    // If this action was explicitly requested, then don't
5860                    // remove things that have it.
5861                    continue;
5862                }
5863                for (int j=i+1; j<N; j++) {
5864                    final ResolveInfo rij = results.get(j);
5865                    if (rij.filter != null && rij.filter.hasAction(action)) {
5866                        results.remove(j);
5867                        if (DEBUG_INTENT_MATCHING) Log.v(
5868                            TAG, "Removing duplicate item from " + j
5869                            + " due to action " + action + " at " + i);
5870                        j--;
5871                        N--;
5872                    }
5873                }
5874            }
5875
5876            // If the caller didn't request filter information, drop it now
5877            // so we don't have to marshall/unmarshall it.
5878            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5879                rii.filter = null;
5880            }
5881        }
5882
5883        // Filter out the caller activity if so requested.
5884        if (caller != null) {
5885            N = results.size();
5886            for (int i=0; i<N; i++) {
5887                ActivityInfo ainfo = results.get(i).activityInfo;
5888                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5889                        && caller.getClassName().equals(ainfo.name)) {
5890                    results.remove(i);
5891                    break;
5892                }
5893            }
5894        }
5895
5896        // If the caller didn't request filter information,
5897        // drop them now so we don't have to
5898        // marshall/unmarshall it.
5899        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5900            N = results.size();
5901            for (int i=0; i<N; i++) {
5902                results.get(i).filter = null;
5903            }
5904        }
5905
5906        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5907        return results;
5908    }
5909
5910    @Override
5911    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5912            String resolvedType, int flags, int userId) {
5913        return new ParceledListSlice<>(
5914                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5915    }
5916
5917    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5918            String resolvedType, int flags, int userId) {
5919        if (!sUserManager.exists(userId)) return Collections.emptyList();
5920        flags = updateFlagsForResolve(flags, userId, intent);
5921        ComponentName comp = intent.getComponent();
5922        if (comp == null) {
5923            if (intent.getSelector() != null) {
5924                intent = intent.getSelector();
5925                comp = intent.getComponent();
5926            }
5927        }
5928        if (comp != null) {
5929            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5930            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5931            if (ai != null) {
5932                ResolveInfo ri = new ResolveInfo();
5933                ri.activityInfo = ai;
5934                list.add(ri);
5935            }
5936            return list;
5937        }
5938
5939        // reader
5940        synchronized (mPackages) {
5941            String pkgName = intent.getPackage();
5942            if (pkgName == null) {
5943                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5944            }
5945            final PackageParser.Package pkg = mPackages.get(pkgName);
5946            if (pkg != null) {
5947                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5948                        userId);
5949            }
5950            return Collections.emptyList();
5951        }
5952    }
5953
5954    @Override
5955    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5956        if (!sUserManager.exists(userId)) return null;
5957        flags = updateFlagsForResolve(flags, userId, intent);
5958        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
5959        if (query != null) {
5960            if (query.size() >= 1) {
5961                // If there is more than one service with the same priority,
5962                // just arbitrarily pick the first one.
5963                return query.get(0);
5964            }
5965        }
5966        return null;
5967    }
5968
5969    @Override
5970    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
5971            String resolvedType, int flags, int userId) {
5972        return new ParceledListSlice<>(
5973                queryIntentServicesInternal(intent, resolvedType, flags, userId));
5974    }
5975
5976    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
5977            String resolvedType, int flags, int userId) {
5978        if (!sUserManager.exists(userId)) return Collections.emptyList();
5979        flags = updateFlagsForResolve(flags, userId, intent);
5980        ComponentName comp = intent.getComponent();
5981        if (comp == null) {
5982            if (intent.getSelector() != null) {
5983                intent = intent.getSelector();
5984                comp = intent.getComponent();
5985            }
5986        }
5987        if (comp != null) {
5988            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5989            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5990            if (si != null) {
5991                final ResolveInfo ri = new ResolveInfo();
5992                ri.serviceInfo = si;
5993                list.add(ri);
5994            }
5995            return list;
5996        }
5997
5998        // reader
5999        synchronized (mPackages) {
6000            String pkgName = intent.getPackage();
6001            if (pkgName == null) {
6002                return mServices.queryIntent(intent, resolvedType, flags, userId);
6003            }
6004            final PackageParser.Package pkg = mPackages.get(pkgName);
6005            if (pkg != null) {
6006                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6007                        userId);
6008            }
6009            return Collections.emptyList();
6010        }
6011    }
6012
6013    @Override
6014    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6015            String resolvedType, int flags, int userId) {
6016        return new ParceledListSlice<>(
6017                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6018    }
6019
6020    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6021            Intent intent, String resolvedType, int flags, int userId) {
6022        if (!sUserManager.exists(userId)) return Collections.emptyList();
6023        flags = updateFlagsForResolve(flags, userId, intent);
6024        ComponentName comp = intent.getComponent();
6025        if (comp == null) {
6026            if (intent.getSelector() != null) {
6027                intent = intent.getSelector();
6028                comp = intent.getComponent();
6029            }
6030        }
6031        if (comp != null) {
6032            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6033            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6034            if (pi != null) {
6035                final ResolveInfo ri = new ResolveInfo();
6036                ri.providerInfo = pi;
6037                list.add(ri);
6038            }
6039            return list;
6040        }
6041
6042        // reader
6043        synchronized (mPackages) {
6044            String pkgName = intent.getPackage();
6045            if (pkgName == null) {
6046                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6047            }
6048            final PackageParser.Package pkg = mPackages.get(pkgName);
6049            if (pkg != null) {
6050                return mProviders.queryIntentForPackage(
6051                        intent, resolvedType, flags, pkg.providers, userId);
6052            }
6053            return Collections.emptyList();
6054        }
6055    }
6056
6057    @Override
6058    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6059        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6060        flags = updateFlagsForPackage(flags, userId, null);
6061        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6062        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6063                true /* requireFullPermission */, false /* checkShell */,
6064                "get installed packages");
6065
6066        // writer
6067        synchronized (mPackages) {
6068            ArrayList<PackageInfo> list;
6069            if (listUninstalled) {
6070                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6071                for (PackageSetting ps : mSettings.mPackages.values()) {
6072                    final PackageInfo pi;
6073                    if (ps.pkg != null) {
6074                        pi = generatePackageInfo(ps, flags, userId);
6075                    } else {
6076                        pi = generatePackageInfo(ps, flags, userId);
6077                    }
6078                    if (pi != null) {
6079                        list.add(pi);
6080                    }
6081                }
6082            } else {
6083                list = new ArrayList<PackageInfo>(mPackages.size());
6084                for (PackageParser.Package p : mPackages.values()) {
6085                    final PackageInfo pi =
6086                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6087                    if (pi != null) {
6088                        list.add(pi);
6089                    }
6090                }
6091            }
6092
6093            return new ParceledListSlice<PackageInfo>(list);
6094        }
6095    }
6096
6097    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6098            String[] permissions, boolean[] tmp, int flags, int userId) {
6099        int numMatch = 0;
6100        final PermissionsState permissionsState = ps.getPermissionsState();
6101        for (int i=0; i<permissions.length; i++) {
6102            final String permission = permissions[i];
6103            if (permissionsState.hasPermission(permission, userId)) {
6104                tmp[i] = true;
6105                numMatch++;
6106            } else {
6107                tmp[i] = false;
6108            }
6109        }
6110        if (numMatch == 0) {
6111            return;
6112        }
6113        final PackageInfo pi;
6114        if (ps.pkg != null) {
6115            pi = generatePackageInfo(ps, flags, userId);
6116        } else {
6117            pi = generatePackageInfo(ps, flags, userId);
6118        }
6119        // The above might return null in cases of uninstalled apps or install-state
6120        // skew across users/profiles.
6121        if (pi != null) {
6122            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6123                if (numMatch == permissions.length) {
6124                    pi.requestedPermissions = permissions;
6125                } else {
6126                    pi.requestedPermissions = new String[numMatch];
6127                    numMatch = 0;
6128                    for (int i=0; i<permissions.length; i++) {
6129                        if (tmp[i]) {
6130                            pi.requestedPermissions[numMatch] = permissions[i];
6131                            numMatch++;
6132                        }
6133                    }
6134                }
6135            }
6136            list.add(pi);
6137        }
6138    }
6139
6140    @Override
6141    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6142            String[] permissions, int flags, int userId) {
6143        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6144        flags = updateFlagsForPackage(flags, userId, permissions);
6145        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6146
6147        // writer
6148        synchronized (mPackages) {
6149            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6150            boolean[] tmpBools = new boolean[permissions.length];
6151            if (listUninstalled) {
6152                for (PackageSetting ps : mSettings.mPackages.values()) {
6153                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6154                }
6155            } else {
6156                for (PackageParser.Package pkg : mPackages.values()) {
6157                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6158                    if (ps != null) {
6159                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6160                                userId);
6161                    }
6162                }
6163            }
6164
6165            return new ParceledListSlice<PackageInfo>(list);
6166        }
6167    }
6168
6169    @Override
6170    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6171        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6172        flags = updateFlagsForApplication(flags, userId, null);
6173        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6174
6175        // writer
6176        synchronized (mPackages) {
6177            ArrayList<ApplicationInfo> list;
6178            if (listUninstalled) {
6179                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6180                for (PackageSetting ps : mSettings.mPackages.values()) {
6181                    ApplicationInfo ai;
6182                    if (ps.pkg != null) {
6183                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6184                                ps.readUserState(userId), userId);
6185                    } else {
6186                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6187                    }
6188                    if (ai != null) {
6189                        list.add(ai);
6190                    }
6191                }
6192            } else {
6193                list = new ArrayList<ApplicationInfo>(mPackages.size());
6194                for (PackageParser.Package p : mPackages.values()) {
6195                    if (p.mExtras != null) {
6196                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6197                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6198                        if (ai != null) {
6199                            list.add(ai);
6200                        }
6201                    }
6202                }
6203            }
6204
6205            return new ParceledListSlice<ApplicationInfo>(list);
6206        }
6207    }
6208
6209    @Override
6210    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6211        if (DISABLE_EPHEMERAL_APPS) {
6212            return null;
6213        }
6214
6215        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6216                "getEphemeralApplications");
6217        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6218                true /* requireFullPermission */, false /* checkShell */,
6219                "getEphemeralApplications");
6220        synchronized (mPackages) {
6221            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6222                    .getEphemeralApplicationsLPw(userId);
6223            if (ephemeralApps != null) {
6224                return new ParceledListSlice<>(ephemeralApps);
6225            }
6226        }
6227        return null;
6228    }
6229
6230    @Override
6231    public boolean isEphemeralApplication(String packageName, int userId) {
6232        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6233                true /* requireFullPermission */, false /* checkShell */,
6234                "isEphemeral");
6235        if (DISABLE_EPHEMERAL_APPS) {
6236            return false;
6237        }
6238
6239        if (!isCallerSameApp(packageName)) {
6240            return false;
6241        }
6242        synchronized (mPackages) {
6243            PackageParser.Package pkg = mPackages.get(packageName);
6244            if (pkg != null) {
6245                return pkg.applicationInfo.isEphemeralApp();
6246            }
6247        }
6248        return false;
6249    }
6250
6251    @Override
6252    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6253        if (DISABLE_EPHEMERAL_APPS) {
6254            return null;
6255        }
6256
6257        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6258                true /* requireFullPermission */, false /* checkShell */,
6259                "getCookie");
6260        if (!isCallerSameApp(packageName)) {
6261            return null;
6262        }
6263        synchronized (mPackages) {
6264            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6265                    packageName, userId);
6266        }
6267    }
6268
6269    @Override
6270    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6271        if (DISABLE_EPHEMERAL_APPS) {
6272            return true;
6273        }
6274
6275        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6276                true /* requireFullPermission */, true /* checkShell */,
6277                "setCookie");
6278        if (!isCallerSameApp(packageName)) {
6279            return false;
6280        }
6281        synchronized (mPackages) {
6282            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6283                    packageName, cookie, userId);
6284        }
6285    }
6286
6287    @Override
6288    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6289        if (DISABLE_EPHEMERAL_APPS) {
6290            return null;
6291        }
6292
6293        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6294                "getEphemeralApplicationIcon");
6295        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6296                true /* requireFullPermission */, false /* checkShell */,
6297                "getEphemeralApplicationIcon");
6298        synchronized (mPackages) {
6299            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6300                    packageName, userId);
6301        }
6302    }
6303
6304    private boolean isCallerSameApp(String packageName) {
6305        PackageParser.Package pkg = mPackages.get(packageName);
6306        return pkg != null
6307                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6308    }
6309
6310    @Override
6311    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6312        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6313    }
6314
6315    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6316        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6317
6318        // reader
6319        synchronized (mPackages) {
6320            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6321            final int userId = UserHandle.getCallingUserId();
6322            while (i.hasNext()) {
6323                final PackageParser.Package p = i.next();
6324                if (p.applicationInfo == null) continue;
6325
6326                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6327                        && !p.applicationInfo.isDirectBootAware();
6328                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6329                        && p.applicationInfo.isDirectBootAware();
6330
6331                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6332                        && (!mSafeMode || isSystemApp(p))
6333                        && (matchesUnaware || matchesAware)) {
6334                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6335                    if (ps != null) {
6336                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6337                                ps.readUserState(userId), userId);
6338                        if (ai != null) {
6339                            finalList.add(ai);
6340                        }
6341                    }
6342                }
6343            }
6344        }
6345
6346        return finalList;
6347    }
6348
6349    @Override
6350    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6351        if (!sUserManager.exists(userId)) return null;
6352        flags = updateFlagsForComponent(flags, userId, name);
6353        // reader
6354        synchronized (mPackages) {
6355            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6356            PackageSetting ps = provider != null
6357                    ? mSettings.mPackages.get(provider.owner.packageName)
6358                    : null;
6359            return ps != null
6360                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6361                    ? PackageParser.generateProviderInfo(provider, flags,
6362                            ps.readUserState(userId), userId)
6363                    : null;
6364        }
6365    }
6366
6367    /**
6368     * @deprecated
6369     */
6370    @Deprecated
6371    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6372        // reader
6373        synchronized (mPackages) {
6374            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6375                    .entrySet().iterator();
6376            final int userId = UserHandle.getCallingUserId();
6377            while (i.hasNext()) {
6378                Map.Entry<String, PackageParser.Provider> entry = i.next();
6379                PackageParser.Provider p = entry.getValue();
6380                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6381
6382                if (ps != null && p.syncable
6383                        && (!mSafeMode || (p.info.applicationInfo.flags
6384                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6385                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6386                            ps.readUserState(userId), userId);
6387                    if (info != null) {
6388                        outNames.add(entry.getKey());
6389                        outInfo.add(info);
6390                    }
6391                }
6392            }
6393        }
6394    }
6395
6396    @Override
6397    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6398            int uid, int flags) {
6399        final int userId = processName != null ? UserHandle.getUserId(uid)
6400                : UserHandle.getCallingUserId();
6401        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6402        flags = updateFlagsForComponent(flags, userId, processName);
6403
6404        ArrayList<ProviderInfo> finalList = null;
6405        // reader
6406        synchronized (mPackages) {
6407            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6408            while (i.hasNext()) {
6409                final PackageParser.Provider p = i.next();
6410                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6411                if (ps != null && p.info.authority != null
6412                        && (processName == null
6413                                || (p.info.processName.equals(processName)
6414                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6415                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6416                    if (finalList == null) {
6417                        finalList = new ArrayList<ProviderInfo>(3);
6418                    }
6419                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6420                            ps.readUserState(userId), userId);
6421                    if (info != null) {
6422                        finalList.add(info);
6423                    }
6424                }
6425            }
6426        }
6427
6428        if (finalList != null) {
6429            Collections.sort(finalList, mProviderInitOrderSorter);
6430            return new ParceledListSlice<ProviderInfo>(finalList);
6431        }
6432
6433        return ParceledListSlice.emptyList();
6434    }
6435
6436    @Override
6437    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6438        // reader
6439        synchronized (mPackages) {
6440            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6441            return PackageParser.generateInstrumentationInfo(i, flags);
6442        }
6443    }
6444
6445    @Override
6446    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6447            String targetPackage, int flags) {
6448        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6449    }
6450
6451    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6452            int flags) {
6453        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6454
6455        // reader
6456        synchronized (mPackages) {
6457            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6458            while (i.hasNext()) {
6459                final PackageParser.Instrumentation p = i.next();
6460                if (targetPackage == null
6461                        || targetPackage.equals(p.info.targetPackage)) {
6462                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6463                            flags);
6464                    if (ii != null) {
6465                        finalList.add(ii);
6466                    }
6467                }
6468            }
6469        }
6470
6471        return finalList;
6472    }
6473
6474    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6475        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6476        if (overlays == null) {
6477            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6478            return;
6479        }
6480        for (PackageParser.Package opkg : overlays.values()) {
6481            // Not much to do if idmap fails: we already logged the error
6482            // and we certainly don't want to abort installation of pkg simply
6483            // because an overlay didn't fit properly. For these reasons,
6484            // ignore the return value of createIdmapForPackagePairLI.
6485            createIdmapForPackagePairLI(pkg, opkg);
6486        }
6487    }
6488
6489    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6490            PackageParser.Package opkg) {
6491        if (!opkg.mTrustedOverlay) {
6492            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6493                    opkg.baseCodePath + ": overlay not trusted");
6494            return false;
6495        }
6496        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6497        if (overlaySet == null) {
6498            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6499                    opkg.baseCodePath + " but target package has no known overlays");
6500            return false;
6501        }
6502        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6503        // TODO: generate idmap for split APKs
6504        try {
6505            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6506        } catch (InstallerException e) {
6507            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6508                    + opkg.baseCodePath);
6509            return false;
6510        }
6511        PackageParser.Package[] overlayArray =
6512            overlaySet.values().toArray(new PackageParser.Package[0]);
6513        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6514            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6515                return p1.mOverlayPriority - p2.mOverlayPriority;
6516            }
6517        };
6518        Arrays.sort(overlayArray, cmp);
6519
6520        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6521        int i = 0;
6522        for (PackageParser.Package p : overlayArray) {
6523            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6524        }
6525        return true;
6526    }
6527
6528    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6529        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6530        try {
6531            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6532        } finally {
6533            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6534        }
6535    }
6536
6537    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6538        final File[] files = dir.listFiles();
6539        if (ArrayUtils.isEmpty(files)) {
6540            Log.d(TAG, "No files in app dir " + dir);
6541            return;
6542        }
6543
6544        if (DEBUG_PACKAGE_SCANNING) {
6545            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6546                    + " flags=0x" + Integer.toHexString(parseFlags));
6547        }
6548
6549        for (File file : files) {
6550            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6551                    && !PackageInstallerService.isStageName(file.getName());
6552            if (!isPackage) {
6553                // Ignore entries which are not packages
6554                continue;
6555            }
6556            try {
6557                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6558                        scanFlags, currentTime, null);
6559            } catch (PackageManagerException e) {
6560                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6561
6562                // Delete invalid userdata apps
6563                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6564                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6565                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6566                    removeCodePathLI(file);
6567                }
6568            }
6569        }
6570    }
6571
6572    private static File getSettingsProblemFile() {
6573        File dataDir = Environment.getDataDirectory();
6574        File systemDir = new File(dataDir, "system");
6575        File fname = new File(systemDir, "uiderrors.txt");
6576        return fname;
6577    }
6578
6579    static void reportSettingsProblem(int priority, String msg) {
6580        logCriticalInfo(priority, msg);
6581    }
6582
6583    static void logCriticalInfo(int priority, String msg) {
6584        Slog.println(priority, TAG, msg);
6585        EventLogTags.writePmCriticalInfo(msg);
6586        try {
6587            File fname = getSettingsProblemFile();
6588            FileOutputStream out = new FileOutputStream(fname, true);
6589            PrintWriter pw = new FastPrintWriter(out);
6590            SimpleDateFormat formatter = new SimpleDateFormat();
6591            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6592            pw.println(dateString + ": " + msg);
6593            pw.close();
6594            FileUtils.setPermissions(
6595                    fname.toString(),
6596                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6597                    -1, -1);
6598        } catch (java.io.IOException e) {
6599        }
6600    }
6601
6602    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6603        if (srcFile.isDirectory()) {
6604            final File baseFile = new File(pkg.baseCodePath);
6605            long maxModifiedTime = baseFile.lastModified();
6606            if (pkg.splitCodePaths != null) {
6607                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6608                    final File splitFile = new File(pkg.splitCodePaths[i]);
6609                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6610                }
6611            }
6612            return maxModifiedTime;
6613        }
6614        return srcFile.lastModified();
6615    }
6616
6617    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6618            final int policyFlags) throws PackageManagerException {
6619        // When upgrading from pre-N MR1, verify the package time stamp using the package
6620        // directory and not the APK file.
6621        final long lastModifiedTime = mIsPreNMR1Upgrade
6622                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
6623        if (ps != null
6624                && ps.codePath.equals(srcFile)
6625                && ps.timeStamp == lastModifiedTime
6626                && !isCompatSignatureUpdateNeeded(pkg)
6627                && !isRecoverSignatureUpdateNeeded(pkg)) {
6628            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6629            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6630            ArraySet<PublicKey> signingKs;
6631            synchronized (mPackages) {
6632                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6633            }
6634            if (ps.signatures.mSignatures != null
6635                    && ps.signatures.mSignatures.length != 0
6636                    && signingKs != null) {
6637                // Optimization: reuse the existing cached certificates
6638                // if the package appears to be unchanged.
6639                pkg.mSignatures = ps.signatures.mSignatures;
6640                pkg.mSigningKeys = signingKs;
6641                return;
6642            }
6643
6644            Slog.w(TAG, "PackageSetting for " + ps.name
6645                    + " is missing signatures.  Collecting certs again to recover them.");
6646        } else {
6647            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
6648        }
6649
6650        try {
6651            PackageParser.collectCertificates(pkg, policyFlags);
6652        } catch (PackageParserException e) {
6653            throw PackageManagerException.from(e);
6654        }
6655    }
6656
6657    /**
6658     *  Traces a package scan.
6659     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6660     */
6661    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6662            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6663        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6664        try {
6665            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6666        } finally {
6667            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6668        }
6669    }
6670
6671    /**
6672     *  Scans a package and returns the newly parsed package.
6673     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6674     */
6675    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6676            long currentTime, UserHandle user) throws PackageManagerException {
6677        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6678        PackageParser pp = new PackageParser();
6679        pp.setSeparateProcesses(mSeparateProcesses);
6680        pp.setOnlyCoreApps(mOnlyCore);
6681        pp.setDisplayMetrics(mMetrics);
6682
6683        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6684            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6685        }
6686
6687        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6688        final PackageParser.Package pkg;
6689        try {
6690            pkg = pp.parsePackage(scanFile, parseFlags);
6691        } catch (PackageParserException e) {
6692            throw PackageManagerException.from(e);
6693        } finally {
6694            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6695        }
6696
6697        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6698    }
6699
6700    /**
6701     *  Scans a package and returns the newly parsed package.
6702     *  @throws PackageManagerException on a parse error.
6703     */
6704    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6705            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6706            throws PackageManagerException {
6707        // If the package has children and this is the first dive in the function
6708        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6709        // packages (parent and children) would be successfully scanned before the
6710        // actual scan since scanning mutates internal state and we want to atomically
6711        // install the package and its children.
6712        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6713            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6714                scanFlags |= SCAN_CHECK_ONLY;
6715            }
6716        } else {
6717            scanFlags &= ~SCAN_CHECK_ONLY;
6718        }
6719
6720        // Scan the parent
6721        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6722                scanFlags, currentTime, user);
6723
6724        // Scan the children
6725        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6726        for (int i = 0; i < childCount; i++) {
6727            PackageParser.Package childPackage = pkg.childPackages.get(i);
6728            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6729                    currentTime, user);
6730        }
6731
6732
6733        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6734            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6735        }
6736
6737        return scannedPkg;
6738    }
6739
6740    /**
6741     *  Scans a package and returns the newly parsed package.
6742     *  @throws PackageManagerException on a parse error.
6743     */
6744    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6745            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6746            throws PackageManagerException {
6747        PackageSetting ps = null;
6748        PackageSetting updatedPkg;
6749        // reader
6750        synchronized (mPackages) {
6751            // Look to see if we already know about this package.
6752            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6753            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6754                // This package has been renamed to its original name.  Let's
6755                // use that.
6756                ps = mSettings.peekPackageLPr(oldName);
6757            }
6758            // If there was no original package, see one for the real package name.
6759            if (ps == null) {
6760                ps = mSettings.peekPackageLPr(pkg.packageName);
6761            }
6762            // Check to see if this package could be hiding/updating a system
6763            // package.  Must look for it either under the original or real
6764            // package name depending on our state.
6765            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6766            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6767
6768            // If this is a package we don't know about on the system partition, we
6769            // may need to remove disabled child packages on the system partition
6770            // or may need to not add child packages if the parent apk is updated
6771            // on the data partition and no longer defines this child package.
6772            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6773                // If this is a parent package for an updated system app and this system
6774                // app got an OTA update which no longer defines some of the child packages
6775                // we have to prune them from the disabled system packages.
6776                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6777                if (disabledPs != null) {
6778                    final int scannedChildCount = (pkg.childPackages != null)
6779                            ? pkg.childPackages.size() : 0;
6780                    final int disabledChildCount = disabledPs.childPackageNames != null
6781                            ? disabledPs.childPackageNames.size() : 0;
6782                    for (int i = 0; i < disabledChildCount; i++) {
6783                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6784                        boolean disabledPackageAvailable = false;
6785                        for (int j = 0; j < scannedChildCount; j++) {
6786                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6787                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6788                                disabledPackageAvailable = true;
6789                                break;
6790                            }
6791                         }
6792                         if (!disabledPackageAvailable) {
6793                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6794                         }
6795                    }
6796                }
6797            }
6798        }
6799
6800        boolean updatedPkgBetter = false;
6801        // First check if this is a system package that may involve an update
6802        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6803            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6804            // it needs to drop FLAG_PRIVILEGED.
6805            if (locationIsPrivileged(scanFile)) {
6806                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6807            } else {
6808                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6809            }
6810
6811            if (ps != null && !ps.codePath.equals(scanFile)) {
6812                // The path has changed from what was last scanned...  check the
6813                // version of the new path against what we have stored to determine
6814                // what to do.
6815                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6816                if (pkg.mVersionCode <= ps.versionCode) {
6817                    // The system package has been updated and the code path does not match
6818                    // Ignore entry. Skip it.
6819                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6820                            + " ignored: updated version " + ps.versionCode
6821                            + " better than this " + pkg.mVersionCode);
6822                    if (!updatedPkg.codePath.equals(scanFile)) {
6823                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6824                                + ps.name + " changing from " + updatedPkg.codePathString
6825                                + " to " + scanFile);
6826                        updatedPkg.codePath = scanFile;
6827                        updatedPkg.codePathString = scanFile.toString();
6828                        updatedPkg.resourcePath = scanFile;
6829                        updatedPkg.resourcePathString = scanFile.toString();
6830                    }
6831                    updatedPkg.pkg = pkg;
6832                    updatedPkg.versionCode = pkg.mVersionCode;
6833
6834                    // Update the disabled system child packages to point to the package too.
6835                    final int childCount = updatedPkg.childPackageNames != null
6836                            ? updatedPkg.childPackageNames.size() : 0;
6837                    for (int i = 0; i < childCount; i++) {
6838                        String childPackageName = updatedPkg.childPackageNames.get(i);
6839                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6840                                childPackageName);
6841                        if (updatedChildPkg != null) {
6842                            updatedChildPkg.pkg = pkg;
6843                            updatedChildPkg.versionCode = pkg.mVersionCode;
6844                        }
6845                    }
6846
6847                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6848                            + scanFile + " ignored: updated version " + ps.versionCode
6849                            + " better than this " + pkg.mVersionCode);
6850                } else {
6851                    // The current app on the system partition is better than
6852                    // what we have updated to on the data partition; switch
6853                    // back to the system partition version.
6854                    // At this point, its safely assumed that package installation for
6855                    // apps in system partition will go through. If not there won't be a working
6856                    // version of the app
6857                    // writer
6858                    synchronized (mPackages) {
6859                        // Just remove the loaded entries from package lists.
6860                        mPackages.remove(ps.name);
6861                    }
6862
6863                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6864                            + " reverting from " + ps.codePathString
6865                            + ": new version " + pkg.mVersionCode
6866                            + " better than installed " + ps.versionCode);
6867
6868                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6869                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6870                    synchronized (mInstallLock) {
6871                        args.cleanUpResourcesLI();
6872                    }
6873                    synchronized (mPackages) {
6874                        mSettings.enableSystemPackageLPw(ps.name);
6875                    }
6876                    updatedPkgBetter = true;
6877                }
6878            }
6879        }
6880
6881        if (updatedPkg != null) {
6882            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6883            // initially
6884            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6885
6886            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6887            // flag set initially
6888            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6889                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6890            }
6891        }
6892
6893        // Verify certificates against what was last scanned
6894        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6895
6896        /*
6897         * A new system app appeared, but we already had a non-system one of the
6898         * same name installed earlier.
6899         */
6900        boolean shouldHideSystemApp = false;
6901        if (updatedPkg == null && ps != null
6902                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6903            /*
6904             * Check to make sure the signatures match first. If they don't,
6905             * wipe the installed application and its data.
6906             */
6907            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6908                    != PackageManager.SIGNATURE_MATCH) {
6909                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6910                        + " signatures don't match existing userdata copy; removing");
6911                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6912                        "scanPackageInternalLI")) {
6913                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6914                }
6915                ps = null;
6916            } else {
6917                /*
6918                 * If the newly-added system app is an older version than the
6919                 * already installed version, hide it. It will be scanned later
6920                 * and re-added like an update.
6921                 */
6922                if (pkg.mVersionCode <= ps.versionCode) {
6923                    shouldHideSystemApp = true;
6924                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6925                            + " but new version " + pkg.mVersionCode + " better than installed "
6926                            + ps.versionCode + "; hiding system");
6927                } else {
6928                    /*
6929                     * The newly found system app is a newer version that the
6930                     * one previously installed. Simply remove the
6931                     * already-installed application and replace it with our own
6932                     * while keeping the application data.
6933                     */
6934                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6935                            + " reverting from " + ps.codePathString + ": new version "
6936                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6937                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6938                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6939                    synchronized (mInstallLock) {
6940                        args.cleanUpResourcesLI();
6941                    }
6942                }
6943            }
6944        }
6945
6946        // The apk is forward locked (not public) if its code and resources
6947        // are kept in different files. (except for app in either system or
6948        // vendor path).
6949        // TODO grab this value from PackageSettings
6950        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6951            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6952                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
6953            }
6954        }
6955
6956        // TODO: extend to support forward-locked splits
6957        String resourcePath = null;
6958        String baseResourcePath = null;
6959        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6960            if (ps != null && ps.resourcePathString != null) {
6961                resourcePath = ps.resourcePathString;
6962                baseResourcePath = ps.resourcePathString;
6963            } else {
6964                // Should not happen at all. Just log an error.
6965                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6966            }
6967        } else {
6968            resourcePath = pkg.codePath;
6969            baseResourcePath = pkg.baseCodePath;
6970        }
6971
6972        // Set application objects path explicitly.
6973        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6974        pkg.setApplicationInfoCodePath(pkg.codePath);
6975        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6976        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6977        pkg.setApplicationInfoResourcePath(resourcePath);
6978        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6979        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6980
6981        // Note that we invoke the following method only if we are about to unpack an application
6982        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
6983                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6984
6985        /*
6986         * If the system app should be overridden by a previously installed
6987         * data, hide the system app now and let the /data/app scan pick it up
6988         * again.
6989         */
6990        if (shouldHideSystemApp) {
6991            synchronized (mPackages) {
6992                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6993            }
6994        }
6995
6996        return scannedPkg;
6997    }
6998
6999    private static String fixProcessName(String defProcessName,
7000            String processName, int uid) {
7001        if (processName == null) {
7002            return defProcessName;
7003        }
7004        return processName;
7005    }
7006
7007    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7008            throws PackageManagerException {
7009        if (pkgSetting.signatures.mSignatures != null) {
7010            // Already existing package. Make sure signatures match
7011            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7012                    == PackageManager.SIGNATURE_MATCH;
7013            if (!match) {
7014                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7015                        == PackageManager.SIGNATURE_MATCH;
7016            }
7017            if (!match) {
7018                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7019                        == PackageManager.SIGNATURE_MATCH;
7020            }
7021            if (!match) {
7022                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7023                        + pkg.packageName + " signatures do not match the "
7024                        + "previously installed version; ignoring!");
7025            }
7026        }
7027
7028        // Check for shared user signatures
7029        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7030            // Already existing package. Make sure signatures match
7031            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7032                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7033            if (!match) {
7034                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7035                        == PackageManager.SIGNATURE_MATCH;
7036            }
7037            if (!match) {
7038                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7039                        == PackageManager.SIGNATURE_MATCH;
7040            }
7041            if (!match) {
7042                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7043                        "Package " + pkg.packageName
7044                        + " has no signatures that match those in shared user "
7045                        + pkgSetting.sharedUser.name + "; ignoring!");
7046            }
7047        }
7048    }
7049
7050    /**
7051     * Enforces that only the system UID or root's UID can call a method exposed
7052     * via Binder.
7053     *
7054     * @param message used as message if SecurityException is thrown
7055     * @throws SecurityException if the caller is not system or root
7056     */
7057    private static final void enforceSystemOrRoot(String message) {
7058        final int uid = Binder.getCallingUid();
7059        if (uid != Process.SYSTEM_UID && uid != 0) {
7060            throw new SecurityException(message);
7061        }
7062    }
7063
7064    @Override
7065    public void performFstrimIfNeeded() {
7066        enforceSystemOrRoot("Only the system can request fstrim");
7067
7068        // Before everything else, see whether we need to fstrim.
7069        try {
7070            IMountService ms = PackageHelper.getMountService();
7071            if (ms != null) {
7072                boolean doTrim = false;
7073                final long interval = android.provider.Settings.Global.getLong(
7074                        mContext.getContentResolver(),
7075                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7076                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7077                if (interval > 0) {
7078                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7079                    if (timeSinceLast > interval) {
7080                        doTrim = true;
7081                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7082                                + "; running immediately");
7083                    }
7084                }
7085                if (doTrim) {
7086                    if (!isFirstBoot()) {
7087                        try {
7088                            ActivityManagerNative.getDefault().showBootMessage(
7089                                    mContext.getResources().getString(
7090                                            R.string.android_upgrading_fstrim), true);
7091                        } catch (RemoteException e) {
7092                        }
7093                    }
7094                    ms.runMaintenance();
7095                }
7096            } else {
7097                Slog.e(TAG, "Mount service unavailable!");
7098            }
7099        } catch (RemoteException e) {
7100            // Can't happen; MountService is local
7101        }
7102    }
7103
7104    @Override
7105    public void updatePackagesIfNeeded() {
7106        enforceSystemOrRoot("Only the system can request package update");
7107
7108        // We need to re-extract after an OTA.
7109        boolean causeUpgrade = isUpgrade();
7110
7111        // First boot or factory reset.
7112        // Note: we also handle devices that are upgrading to N right now as if it is their
7113        //       first boot, as they do not have profile data.
7114        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7115
7116        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7117        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7118
7119        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7120            return;
7121        }
7122
7123        List<PackageParser.Package> pkgs;
7124        synchronized (mPackages) {
7125            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7126        }
7127
7128        final long startTime = System.nanoTime();
7129        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7130                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7131
7132        final int elapsedTimeSeconds =
7133                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7134
7135        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7136        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7137        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7138        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7139        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7140    }
7141
7142    /**
7143     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7144     * containing statistics about the invocation. The array consists of three elements,
7145     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7146     * and {@code numberOfPackagesFailed}.
7147     */
7148    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7149            String compilerFilter) {
7150
7151        int numberOfPackagesVisited = 0;
7152        int numberOfPackagesOptimized = 0;
7153        int numberOfPackagesSkipped = 0;
7154        int numberOfPackagesFailed = 0;
7155        final int numberOfPackagesToDexopt = pkgs.size();
7156
7157        for (PackageParser.Package pkg : pkgs) {
7158            numberOfPackagesVisited++;
7159
7160            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7161                if (DEBUG_DEXOPT) {
7162                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7163                }
7164                numberOfPackagesSkipped++;
7165                continue;
7166            }
7167
7168            if (DEBUG_DEXOPT) {
7169                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7170                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7171            }
7172
7173            if (showDialog) {
7174                try {
7175                    ActivityManagerNative.getDefault().showBootMessage(
7176                            mContext.getResources().getString(R.string.android_upgrading_apk,
7177                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7178                } catch (RemoteException e) {
7179                }
7180            }
7181
7182            // If the OTA updates a system app which was previously preopted to a non-preopted state
7183            // the app might end up being verified at runtime. That's because by default the apps
7184            // are verify-profile but for preopted apps there's no profile.
7185            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7186            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7187            // filter (by default interpret-only).
7188            // Note that at this stage unused apps are already filtered.
7189            if (isSystemApp(pkg) &&
7190                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7191                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7192                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7193            }
7194
7195            // checkProfiles is false to avoid merging profiles during boot which
7196            // might interfere with background compilation (b/28612421).
7197            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7198            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7199            // trade-off worth doing to save boot time work.
7200            int dexOptStatus = performDexOptTraced(pkg.packageName,
7201                    false /* checkProfiles */,
7202                    compilerFilter,
7203                    false /* force */);
7204            switch (dexOptStatus) {
7205                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7206                    numberOfPackagesOptimized++;
7207                    break;
7208                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7209                    numberOfPackagesSkipped++;
7210                    break;
7211                case PackageDexOptimizer.DEX_OPT_FAILED:
7212                    numberOfPackagesFailed++;
7213                    break;
7214                default:
7215                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7216                    break;
7217            }
7218        }
7219
7220        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7221                numberOfPackagesFailed };
7222    }
7223
7224    @Override
7225    public void notifyPackageUse(String packageName, int reason) {
7226        synchronized (mPackages) {
7227            PackageParser.Package p = mPackages.get(packageName);
7228            if (p == null) {
7229                return;
7230            }
7231            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7232        }
7233    }
7234
7235    // TODO: this is not used nor needed. Delete it.
7236    @Override
7237    public boolean performDexOptIfNeeded(String packageName) {
7238        int dexOptStatus = performDexOptTraced(packageName,
7239                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7240        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7241    }
7242
7243    @Override
7244    public boolean performDexOpt(String packageName,
7245            boolean checkProfiles, int compileReason, boolean force) {
7246        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7247                getCompilerFilterForReason(compileReason), force);
7248        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7249    }
7250
7251    @Override
7252    public boolean performDexOptMode(String packageName,
7253            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7254        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7255                targetCompilerFilter, force);
7256        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7257    }
7258
7259    private int performDexOptTraced(String packageName,
7260                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7261        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7262        try {
7263            return performDexOptInternal(packageName, checkProfiles,
7264                    targetCompilerFilter, force);
7265        } finally {
7266            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7267        }
7268    }
7269
7270    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7271    // if the package can now be considered up to date for the given filter.
7272    private int performDexOptInternal(String packageName,
7273                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7274        PackageParser.Package p;
7275        synchronized (mPackages) {
7276            p = mPackages.get(packageName);
7277            if (p == null) {
7278                // Package could not be found. Report failure.
7279                return PackageDexOptimizer.DEX_OPT_FAILED;
7280            }
7281            mPackageUsage.maybeWriteAsync(mPackages);
7282            mCompilerStats.maybeWriteAsync();
7283        }
7284        long callingId = Binder.clearCallingIdentity();
7285        try {
7286            synchronized (mInstallLock) {
7287                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7288                        targetCompilerFilter, force);
7289            }
7290        } finally {
7291            Binder.restoreCallingIdentity(callingId);
7292        }
7293    }
7294
7295    public ArraySet<String> getOptimizablePackages() {
7296        ArraySet<String> pkgs = new ArraySet<String>();
7297        synchronized (mPackages) {
7298            for (PackageParser.Package p : mPackages.values()) {
7299                if (PackageDexOptimizer.canOptimizePackage(p)) {
7300                    pkgs.add(p.packageName);
7301                }
7302            }
7303        }
7304        return pkgs;
7305    }
7306
7307    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7308            boolean checkProfiles, String targetCompilerFilter,
7309            boolean force) {
7310        // Select the dex optimizer based on the force parameter.
7311        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7312        //       allocate an object here.
7313        PackageDexOptimizer pdo = force
7314                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7315                : mPackageDexOptimizer;
7316
7317        // Optimize all dependencies first. Note: we ignore the return value and march on
7318        // on errors.
7319        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7320        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7321        if (!deps.isEmpty()) {
7322            for (PackageParser.Package depPackage : deps) {
7323                // TODO: Analyze and investigate if we (should) profile libraries.
7324                // Currently this will do a full compilation of the library by default.
7325                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7326                        false /* checkProfiles */,
7327                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7328                        getOrCreateCompilerPackageStats(depPackage));
7329            }
7330        }
7331        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7332                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7333    }
7334
7335    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7336        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7337            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7338            Set<String> collectedNames = new HashSet<>();
7339            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7340
7341            retValue.remove(p);
7342
7343            return retValue;
7344        } else {
7345            return Collections.emptyList();
7346        }
7347    }
7348
7349    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7350            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7351        if (!collectedNames.contains(p.packageName)) {
7352            collectedNames.add(p.packageName);
7353            collected.add(p);
7354
7355            if (p.usesLibraries != null) {
7356                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7357            }
7358            if (p.usesOptionalLibraries != null) {
7359                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7360                        collectedNames);
7361            }
7362        }
7363    }
7364
7365    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7366            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7367        for (String libName : libs) {
7368            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7369            if (libPkg != null) {
7370                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7371            }
7372        }
7373    }
7374
7375    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7376        synchronized (mPackages) {
7377            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7378            if (lib != null && lib.apk != null) {
7379                return mPackages.get(lib.apk);
7380            }
7381        }
7382        return null;
7383    }
7384
7385    public void shutdown() {
7386        mPackageUsage.writeNow(mPackages);
7387        mCompilerStats.writeNow();
7388    }
7389
7390    @Override
7391    public void dumpProfiles(String packageName) {
7392        PackageParser.Package pkg;
7393        synchronized (mPackages) {
7394            pkg = mPackages.get(packageName);
7395            if (pkg == null) {
7396                throw new IllegalArgumentException("Unknown package: " + packageName);
7397            }
7398        }
7399        /* Only the shell, root, or the app user should be able to dump profiles. */
7400        int callingUid = Binder.getCallingUid();
7401        if (callingUid != Process.SHELL_UID &&
7402            callingUid != Process.ROOT_UID &&
7403            callingUid != pkg.applicationInfo.uid) {
7404            throw new SecurityException("dumpProfiles");
7405        }
7406
7407        synchronized (mInstallLock) {
7408            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7409            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7410            try {
7411                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7412                String gid = Integer.toString(sharedGid);
7413                String codePaths = TextUtils.join(";", allCodePaths);
7414                mInstaller.dumpProfiles(gid, packageName, codePaths);
7415            } catch (InstallerException e) {
7416                Slog.w(TAG, "Failed to dump profiles", e);
7417            }
7418            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7419        }
7420    }
7421
7422    @Override
7423    public void forceDexOpt(String packageName) {
7424        enforceSystemOrRoot("forceDexOpt");
7425
7426        PackageParser.Package pkg;
7427        synchronized (mPackages) {
7428            pkg = mPackages.get(packageName);
7429            if (pkg == null) {
7430                throw new IllegalArgumentException("Unknown package: " + packageName);
7431            }
7432        }
7433
7434        synchronized (mInstallLock) {
7435            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7436
7437            // Whoever is calling forceDexOpt wants a fully compiled package.
7438            // Don't use profiles since that may cause compilation to be skipped.
7439            final int res = performDexOptInternalWithDependenciesLI(pkg,
7440                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7441                    true /* force */);
7442
7443            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7444            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7445                throw new IllegalStateException("Failed to dexopt: " + res);
7446            }
7447        }
7448    }
7449
7450    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7451        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7452            Slog.w(TAG, "Unable to update from " + oldPkg.name
7453                    + " to " + newPkg.packageName
7454                    + ": old package not in system partition");
7455            return false;
7456        } else if (mPackages.get(oldPkg.name) != null) {
7457            Slog.w(TAG, "Unable to update from " + oldPkg.name
7458                    + " to " + newPkg.packageName
7459                    + ": old package still exists");
7460            return false;
7461        }
7462        return true;
7463    }
7464
7465    void removeCodePathLI(File codePath) {
7466        if (codePath.isDirectory()) {
7467            try {
7468                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7469            } catch (InstallerException e) {
7470                Slog.w(TAG, "Failed to remove code path", e);
7471            }
7472        } else {
7473            codePath.delete();
7474        }
7475    }
7476
7477    private int[] resolveUserIds(int userId) {
7478        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7479    }
7480
7481    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7482        if (pkg == null) {
7483            Slog.wtf(TAG, "Package was null!", new Throwable());
7484            return;
7485        }
7486        clearAppDataLeafLIF(pkg, userId, flags);
7487        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7488        for (int i = 0; i < childCount; i++) {
7489            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7490        }
7491    }
7492
7493    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7494        final PackageSetting ps;
7495        synchronized (mPackages) {
7496            ps = mSettings.mPackages.get(pkg.packageName);
7497        }
7498        for (int realUserId : resolveUserIds(userId)) {
7499            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7500            try {
7501                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7502                        ceDataInode);
7503            } catch (InstallerException e) {
7504                Slog.w(TAG, String.valueOf(e));
7505            }
7506        }
7507    }
7508
7509    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7510        if (pkg == null) {
7511            Slog.wtf(TAG, "Package was null!", new Throwable());
7512            return;
7513        }
7514        destroyAppDataLeafLIF(pkg, userId, flags);
7515        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7516        for (int i = 0; i < childCount; i++) {
7517            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7518        }
7519    }
7520
7521    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7522        final PackageSetting ps;
7523        synchronized (mPackages) {
7524            ps = mSettings.mPackages.get(pkg.packageName);
7525        }
7526        for (int realUserId : resolveUserIds(userId)) {
7527            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7528            try {
7529                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7530                        ceDataInode);
7531            } catch (InstallerException e) {
7532                Slog.w(TAG, String.valueOf(e));
7533            }
7534        }
7535    }
7536
7537    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7538        if (pkg == null) {
7539            Slog.wtf(TAG, "Package was null!", new Throwable());
7540            return;
7541        }
7542        destroyAppProfilesLeafLIF(pkg);
7543        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7544        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7545        for (int i = 0; i < childCount; i++) {
7546            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7547            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7548                    true /* removeBaseMarker */);
7549        }
7550    }
7551
7552    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7553            boolean removeBaseMarker) {
7554        if (pkg.isForwardLocked()) {
7555            return;
7556        }
7557
7558        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7559            try {
7560                path = PackageManagerServiceUtils.realpath(new File(path));
7561            } catch (IOException e) {
7562                // TODO: Should we return early here ?
7563                Slog.w(TAG, "Failed to get canonical path", e);
7564                continue;
7565            }
7566
7567            final String useMarker = path.replace('/', '@');
7568            for (int realUserId : resolveUserIds(userId)) {
7569                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7570                if (removeBaseMarker) {
7571                    File foreignUseMark = new File(profileDir, useMarker);
7572                    if (foreignUseMark.exists()) {
7573                        if (!foreignUseMark.delete()) {
7574                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7575                                    + pkg.packageName);
7576                        }
7577                    }
7578                }
7579
7580                File[] markers = profileDir.listFiles();
7581                if (markers != null) {
7582                    final String searchString = "@" + pkg.packageName + "@";
7583                    // We also delete all markers that contain the package name we're
7584                    // uninstalling. These are associated with secondary dex-files belonging
7585                    // to the package. Reconstructing the path of these dex files is messy
7586                    // in general.
7587                    for (File marker : markers) {
7588                        if (marker.getName().indexOf(searchString) > 0) {
7589                            if (!marker.delete()) {
7590                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7591                                    + pkg.packageName);
7592                            }
7593                        }
7594                    }
7595                }
7596            }
7597        }
7598    }
7599
7600    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7601        try {
7602            mInstaller.destroyAppProfiles(pkg.packageName);
7603        } catch (InstallerException e) {
7604            Slog.w(TAG, String.valueOf(e));
7605        }
7606    }
7607
7608    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7609        if (pkg == null) {
7610            Slog.wtf(TAG, "Package was null!", new Throwable());
7611            return;
7612        }
7613        clearAppProfilesLeafLIF(pkg);
7614        // We don't remove the base foreign use marker when clearing profiles because
7615        // we will rename it when the app is updated. Unlike the actual profile contents,
7616        // the foreign use marker is good across installs.
7617        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7618        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7619        for (int i = 0; i < childCount; i++) {
7620            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7621        }
7622    }
7623
7624    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7625        try {
7626            mInstaller.clearAppProfiles(pkg.packageName);
7627        } catch (InstallerException e) {
7628            Slog.w(TAG, String.valueOf(e));
7629        }
7630    }
7631
7632    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7633            long lastUpdateTime) {
7634        // Set parent install/update time
7635        PackageSetting ps = (PackageSetting) pkg.mExtras;
7636        if (ps != null) {
7637            ps.firstInstallTime = firstInstallTime;
7638            ps.lastUpdateTime = lastUpdateTime;
7639        }
7640        // Set children install/update time
7641        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7642        for (int i = 0; i < childCount; i++) {
7643            PackageParser.Package childPkg = pkg.childPackages.get(i);
7644            ps = (PackageSetting) childPkg.mExtras;
7645            if (ps != null) {
7646                ps.firstInstallTime = firstInstallTime;
7647                ps.lastUpdateTime = lastUpdateTime;
7648            }
7649        }
7650    }
7651
7652    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7653            PackageParser.Package changingLib) {
7654        if (file.path != null) {
7655            usesLibraryFiles.add(file.path);
7656            return;
7657        }
7658        PackageParser.Package p = mPackages.get(file.apk);
7659        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7660            // If we are doing this while in the middle of updating a library apk,
7661            // then we need to make sure to use that new apk for determining the
7662            // dependencies here.  (We haven't yet finished committing the new apk
7663            // to the package manager state.)
7664            if (p == null || p.packageName.equals(changingLib.packageName)) {
7665                p = changingLib;
7666            }
7667        }
7668        if (p != null) {
7669            usesLibraryFiles.addAll(p.getAllCodePaths());
7670        }
7671    }
7672
7673    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7674            PackageParser.Package changingLib) throws PackageManagerException {
7675        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7676            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7677            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7678            for (int i=0; i<N; i++) {
7679                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7680                if (file == null) {
7681                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7682                            "Package " + pkg.packageName + " requires unavailable shared library "
7683                            + pkg.usesLibraries.get(i) + "; failing!");
7684                }
7685                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7686            }
7687            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7688            for (int i=0; i<N; i++) {
7689                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7690                if (file == null) {
7691                    Slog.w(TAG, "Package " + pkg.packageName
7692                            + " desires unavailable shared library "
7693                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7694                } else {
7695                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7696                }
7697            }
7698            N = usesLibraryFiles.size();
7699            if (N > 0) {
7700                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7701            } else {
7702                pkg.usesLibraryFiles = null;
7703            }
7704        }
7705    }
7706
7707    private static boolean hasString(List<String> list, List<String> which) {
7708        if (list == null) {
7709            return false;
7710        }
7711        for (int i=list.size()-1; i>=0; i--) {
7712            for (int j=which.size()-1; j>=0; j--) {
7713                if (which.get(j).equals(list.get(i))) {
7714                    return true;
7715                }
7716            }
7717        }
7718        return false;
7719    }
7720
7721    private void updateAllSharedLibrariesLPw() {
7722        for (PackageParser.Package pkg : mPackages.values()) {
7723            try {
7724                updateSharedLibrariesLPw(pkg, null);
7725            } catch (PackageManagerException e) {
7726                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7727            }
7728        }
7729    }
7730
7731    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7732            PackageParser.Package changingPkg) {
7733        ArrayList<PackageParser.Package> res = null;
7734        for (PackageParser.Package pkg : mPackages.values()) {
7735            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7736                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7737                if (res == null) {
7738                    res = new ArrayList<PackageParser.Package>();
7739                }
7740                res.add(pkg);
7741                try {
7742                    updateSharedLibrariesLPw(pkg, changingPkg);
7743                } catch (PackageManagerException e) {
7744                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7745                }
7746            }
7747        }
7748        return res;
7749    }
7750
7751    /**
7752     * Derive the value of the {@code cpuAbiOverride} based on the provided
7753     * value and an optional stored value from the package settings.
7754     */
7755    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7756        String cpuAbiOverride = null;
7757
7758        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7759            cpuAbiOverride = null;
7760        } else if (abiOverride != null) {
7761            cpuAbiOverride = abiOverride;
7762        } else if (settings != null) {
7763            cpuAbiOverride = settings.cpuAbiOverrideString;
7764        }
7765
7766        return cpuAbiOverride;
7767    }
7768
7769    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7770            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7771                    throws PackageManagerException {
7772        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7773        // If the package has children and this is the first dive in the function
7774        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7775        // whether all packages (parent and children) would be successfully scanned
7776        // before the actual scan since scanning mutates internal state and we want
7777        // to atomically install the package and its children.
7778        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7779            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7780                scanFlags |= SCAN_CHECK_ONLY;
7781            }
7782        } else {
7783            scanFlags &= ~SCAN_CHECK_ONLY;
7784        }
7785
7786        final PackageParser.Package scannedPkg;
7787        try {
7788            // Scan the parent
7789            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7790            // Scan the children
7791            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7792            for (int i = 0; i < childCount; i++) {
7793                PackageParser.Package childPkg = pkg.childPackages.get(i);
7794                scanPackageLI(childPkg, policyFlags,
7795                        scanFlags, currentTime, user);
7796            }
7797        } finally {
7798            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7799        }
7800
7801        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7802            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7803        }
7804
7805        return scannedPkg;
7806    }
7807
7808    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7809            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7810        boolean success = false;
7811        try {
7812            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7813                    currentTime, user);
7814            success = true;
7815            return res;
7816        } finally {
7817            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7818                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7819                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7820                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7821                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7822            }
7823        }
7824    }
7825
7826    /**
7827     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7828     */
7829    private static boolean apkHasCode(String fileName) {
7830        StrictJarFile jarFile = null;
7831        try {
7832            jarFile = new StrictJarFile(fileName,
7833                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7834            return jarFile.findEntry("classes.dex") != null;
7835        } catch (IOException ignore) {
7836        } finally {
7837            try {
7838                if (jarFile != null) {
7839                    jarFile.close();
7840                }
7841            } catch (IOException ignore) {}
7842        }
7843        return false;
7844    }
7845
7846    /**
7847     * Enforces code policy for the package. This ensures that if an APK has
7848     * declared hasCode="true" in its manifest that the APK actually contains
7849     * code.
7850     *
7851     * @throws PackageManagerException If bytecode could not be found when it should exist
7852     */
7853    private static void enforceCodePolicy(PackageParser.Package pkg)
7854            throws PackageManagerException {
7855        final boolean shouldHaveCode =
7856                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7857        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7858            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7859                    "Package " + pkg.baseCodePath + " code is missing");
7860        }
7861
7862        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7863            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7864                final boolean splitShouldHaveCode =
7865                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7866                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7867                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7868                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7869                }
7870            }
7871        }
7872    }
7873
7874    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7875            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7876            throws PackageManagerException {
7877        final File scanFile = new File(pkg.codePath);
7878        if (pkg.applicationInfo.getCodePath() == null ||
7879                pkg.applicationInfo.getResourcePath() == null) {
7880            // Bail out. The resource and code paths haven't been set.
7881            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7882                    "Code and resource paths haven't been set correctly");
7883        }
7884
7885        // Apply policy
7886        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7887            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7888            if (pkg.applicationInfo.isDirectBootAware()) {
7889                // we're direct boot aware; set for all components
7890                for (PackageParser.Service s : pkg.services) {
7891                    s.info.encryptionAware = s.info.directBootAware = true;
7892                }
7893                for (PackageParser.Provider p : pkg.providers) {
7894                    p.info.encryptionAware = p.info.directBootAware = true;
7895                }
7896                for (PackageParser.Activity a : pkg.activities) {
7897                    a.info.encryptionAware = a.info.directBootAware = true;
7898                }
7899                for (PackageParser.Activity r : pkg.receivers) {
7900                    r.info.encryptionAware = r.info.directBootAware = true;
7901                }
7902            }
7903        } else {
7904            // Only allow system apps to be flagged as core apps.
7905            pkg.coreApp = false;
7906            // clear flags not applicable to regular apps
7907            pkg.applicationInfo.privateFlags &=
7908                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7909            pkg.applicationInfo.privateFlags &=
7910                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7911        }
7912        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7913
7914        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7915            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7916        }
7917
7918        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7919            enforceCodePolicy(pkg);
7920        }
7921
7922        if (mCustomResolverComponentName != null &&
7923                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7924            setUpCustomResolverActivity(pkg);
7925        }
7926
7927        if (pkg.packageName.equals("android")) {
7928            synchronized (mPackages) {
7929                if (mAndroidApplication != null) {
7930                    Slog.w(TAG, "*************************************************");
7931                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7932                    Slog.w(TAG, " file=" + scanFile);
7933                    Slog.w(TAG, "*************************************************");
7934                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7935                            "Core android package being redefined.  Skipping.");
7936                }
7937
7938                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7939                    // Set up information for our fall-back user intent resolution activity.
7940                    mPlatformPackage = pkg;
7941                    pkg.mVersionCode = mSdkVersion;
7942                    mAndroidApplication = pkg.applicationInfo;
7943
7944                    if (!mResolverReplaced) {
7945                        mResolveActivity.applicationInfo = mAndroidApplication;
7946                        mResolveActivity.name = ResolverActivity.class.getName();
7947                        mResolveActivity.packageName = mAndroidApplication.packageName;
7948                        mResolveActivity.processName = "system:ui";
7949                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7950                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7951                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7952                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
7953                        mResolveActivity.exported = true;
7954                        mResolveActivity.enabled = true;
7955                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
7956                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
7957                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
7958                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
7959                                | ActivityInfo.CONFIG_ORIENTATION
7960                                | ActivityInfo.CONFIG_KEYBOARD
7961                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
7962                        mResolveInfo.activityInfo = mResolveActivity;
7963                        mResolveInfo.priority = 0;
7964                        mResolveInfo.preferredOrder = 0;
7965                        mResolveInfo.match = 0;
7966                        mResolveComponentName = new ComponentName(
7967                                mAndroidApplication.packageName, mResolveActivity.name);
7968                    }
7969                }
7970            }
7971        }
7972
7973        if (DEBUG_PACKAGE_SCANNING) {
7974            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7975                Log.d(TAG, "Scanning package " + pkg.packageName);
7976        }
7977
7978        synchronized (mPackages) {
7979            if (mPackages.containsKey(pkg.packageName)
7980                    || mSharedLibraries.containsKey(pkg.packageName)) {
7981                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7982                        "Application package " + pkg.packageName
7983                                + " already installed.  Skipping duplicate.");
7984            }
7985
7986            // If we're only installing presumed-existing packages, require that the
7987            // scanned APK is both already known and at the path previously established
7988            // for it.  Previously unknown packages we pick up normally, but if we have an
7989            // a priori expectation about this package's install presence, enforce it.
7990            // With a singular exception for new system packages. When an OTA contains
7991            // a new system package, we allow the codepath to change from a system location
7992            // to the user-installed location. If we don't allow this change, any newer,
7993            // user-installed version of the application will be ignored.
7994            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7995                if (mExpectingBetter.containsKey(pkg.packageName)) {
7996                    logCriticalInfo(Log.WARN,
7997                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7998                } else {
7999                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8000                    if (known != null) {
8001                        if (DEBUG_PACKAGE_SCANNING) {
8002                            Log.d(TAG, "Examining " + pkg.codePath
8003                                    + " and requiring known paths " + known.codePathString
8004                                    + " & " + known.resourcePathString);
8005                        }
8006                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8007                                || !pkg.applicationInfo.getResourcePath().equals(
8008                                known.resourcePathString)) {
8009                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8010                                    "Application package " + pkg.packageName
8011                                            + " found at " + pkg.applicationInfo.getCodePath()
8012                                            + " but expected at " + known.codePathString
8013                                            + "; ignoring.");
8014                        }
8015                    }
8016                }
8017            }
8018        }
8019
8020        // Initialize package source and resource directories
8021        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8022        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8023
8024        SharedUserSetting suid = null;
8025        PackageSetting pkgSetting = null;
8026
8027        if (!isSystemApp(pkg)) {
8028            // Only system apps can use these features.
8029            pkg.mOriginalPackages = null;
8030            pkg.mRealPackage = null;
8031            pkg.mAdoptPermissions = null;
8032        }
8033
8034        // Getting the package setting may have a side-effect, so if we
8035        // are only checking if scan would succeed, stash a copy of the
8036        // old setting to restore at the end.
8037        PackageSetting nonMutatedPs = null;
8038
8039        // writer
8040        synchronized (mPackages) {
8041            if (pkg.mSharedUserId != null) {
8042                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8043                if (suid == null) {
8044                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8045                            "Creating application package " + pkg.packageName
8046                            + " for shared user failed");
8047                }
8048                if (DEBUG_PACKAGE_SCANNING) {
8049                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8050                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8051                                + "): packages=" + suid.packages);
8052                }
8053            }
8054
8055            // Check if we are renaming from an original package name.
8056            PackageSetting origPackage = null;
8057            String realName = null;
8058            if (pkg.mOriginalPackages != null) {
8059                // This package may need to be renamed to a previously
8060                // installed name.  Let's check on that...
8061                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8062                if (pkg.mOriginalPackages.contains(renamed)) {
8063                    // This package had originally been installed as the
8064                    // original name, and we have already taken care of
8065                    // transitioning to the new one.  Just update the new
8066                    // one to continue using the old name.
8067                    realName = pkg.mRealPackage;
8068                    if (!pkg.packageName.equals(renamed)) {
8069                        // Callers into this function may have already taken
8070                        // care of renaming the package; only do it here if
8071                        // it is not already done.
8072                        pkg.setPackageName(renamed);
8073                    }
8074
8075                } else {
8076                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8077                        if ((origPackage = mSettings.peekPackageLPr(
8078                                pkg.mOriginalPackages.get(i))) != null) {
8079                            // We do have the package already installed under its
8080                            // original name...  should we use it?
8081                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8082                                // New package is not compatible with original.
8083                                origPackage = null;
8084                                continue;
8085                            } else if (origPackage.sharedUser != null) {
8086                                // Make sure uid is compatible between packages.
8087                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8088                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8089                                            + " to " + pkg.packageName + ": old uid "
8090                                            + origPackage.sharedUser.name
8091                                            + " differs from " + pkg.mSharedUserId);
8092                                    origPackage = null;
8093                                    continue;
8094                                }
8095                                // TODO: Add case when shared user id is added [b/28144775]
8096                            } else {
8097                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8098                                        + pkg.packageName + " to old name " + origPackage.name);
8099                            }
8100                            break;
8101                        }
8102                    }
8103                }
8104            }
8105
8106            if (mTransferedPackages.contains(pkg.packageName)) {
8107                Slog.w(TAG, "Package " + pkg.packageName
8108                        + " was transferred to another, but its .apk remains");
8109            }
8110
8111            // See comments in nonMutatedPs declaration
8112            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8113                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8114                if (foundPs != null) {
8115                    nonMutatedPs = new PackageSetting(foundPs);
8116                }
8117            }
8118
8119            // Just create the setting, don't add it yet. For already existing packages
8120            // the PkgSetting exists already and doesn't have to be created.
8121            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8122                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8123                    pkg.applicationInfo.primaryCpuAbi,
8124                    pkg.applicationInfo.secondaryCpuAbi,
8125                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8126                    user, false);
8127            if (pkgSetting == null) {
8128                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8129                        "Creating application package " + pkg.packageName + " failed");
8130            }
8131
8132            if (pkgSetting.origPackage != null) {
8133                // If we are first transitioning from an original package,
8134                // fix up the new package's name now.  We need to do this after
8135                // looking up the package under its new name, so getPackageLP
8136                // can take care of fiddling things correctly.
8137                pkg.setPackageName(origPackage.name);
8138
8139                // File a report about this.
8140                String msg = "New package " + pkgSetting.realName
8141                        + " renamed to replace old package " + pkgSetting.name;
8142                reportSettingsProblem(Log.WARN, msg);
8143
8144                // Make a note of it.
8145                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8146                    mTransferedPackages.add(origPackage.name);
8147                }
8148
8149                // No longer need to retain this.
8150                pkgSetting.origPackage = null;
8151            }
8152
8153            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8154                // Make a note of it.
8155                mTransferedPackages.add(pkg.packageName);
8156            }
8157
8158            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8159                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8160            }
8161
8162            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8163                // Check all shared libraries and map to their actual file path.
8164                // We only do this here for apps not on a system dir, because those
8165                // are the only ones that can fail an install due to this.  We
8166                // will take care of the system apps by updating all of their
8167                // library paths after the scan is done.
8168                updateSharedLibrariesLPw(pkg, null);
8169            }
8170
8171            if (mFoundPolicyFile) {
8172                SELinuxMMAC.assignSeinfoValue(pkg);
8173            }
8174
8175            pkg.applicationInfo.uid = pkgSetting.appId;
8176            pkg.mExtras = pkgSetting;
8177            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8178                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8179                    // We just determined the app is signed correctly, so bring
8180                    // over the latest parsed certs.
8181                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8182                } else {
8183                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8184                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8185                                "Package " + pkg.packageName + " upgrade keys do not match the "
8186                                + "previously installed version");
8187                    } else {
8188                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8189                        String msg = "System package " + pkg.packageName
8190                            + " signature changed; retaining data.";
8191                        reportSettingsProblem(Log.WARN, msg);
8192                    }
8193                }
8194            } else {
8195                try {
8196                    verifySignaturesLP(pkgSetting, pkg);
8197                    // We just determined the app is signed correctly, so bring
8198                    // over the latest parsed certs.
8199                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8200                } catch (PackageManagerException e) {
8201                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8202                        throw e;
8203                    }
8204                    // The signature has changed, but this package is in the system
8205                    // image...  let's recover!
8206                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8207                    // However...  if this package is part of a shared user, but it
8208                    // doesn't match the signature of the shared user, let's fail.
8209                    // What this means is that you can't change the signatures
8210                    // associated with an overall shared user, which doesn't seem all
8211                    // that unreasonable.
8212                    if (pkgSetting.sharedUser != null) {
8213                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8214                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8215                            throw new PackageManagerException(
8216                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8217                                            "Signature mismatch for shared user: "
8218                                            + pkgSetting.sharedUser);
8219                        }
8220                    }
8221                    // File a report about this.
8222                    String msg = "System package " + pkg.packageName
8223                        + " signature changed; retaining data.";
8224                    reportSettingsProblem(Log.WARN, msg);
8225                }
8226            }
8227            // Verify that this new package doesn't have any content providers
8228            // that conflict with existing packages.  Only do this if the
8229            // package isn't already installed, since we don't want to break
8230            // things that are installed.
8231            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8232                final int N = pkg.providers.size();
8233                int i;
8234                for (i=0; i<N; i++) {
8235                    PackageParser.Provider p = pkg.providers.get(i);
8236                    if (p.info.authority != null) {
8237                        String names[] = p.info.authority.split(";");
8238                        for (int j = 0; j < names.length; j++) {
8239                            if (mProvidersByAuthority.containsKey(names[j])) {
8240                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8241                                final String otherPackageName =
8242                                        ((other != null && other.getComponentName() != null) ?
8243                                                other.getComponentName().getPackageName() : "?");
8244                                throw new PackageManagerException(
8245                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8246                                                "Can't install because provider name " + names[j]
8247                                                + " (in package " + pkg.applicationInfo.packageName
8248                                                + ") is already used by " + otherPackageName);
8249                            }
8250                        }
8251                    }
8252                }
8253            }
8254
8255            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8256                // This package wants to adopt ownership of permissions from
8257                // another package.
8258                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8259                    final String origName = pkg.mAdoptPermissions.get(i);
8260                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8261                    if (orig != null) {
8262                        if (verifyPackageUpdateLPr(orig, pkg)) {
8263                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8264                                    + pkg.packageName);
8265                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8266                        }
8267                    }
8268                }
8269            }
8270        }
8271
8272        final String pkgName = pkg.packageName;
8273
8274        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8275        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8276        pkg.applicationInfo.processName = fixProcessName(
8277                pkg.applicationInfo.packageName,
8278                pkg.applicationInfo.processName,
8279                pkg.applicationInfo.uid);
8280
8281        if (pkg != mPlatformPackage) {
8282            // Get all of our default paths setup
8283            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8284        }
8285
8286        final String path = scanFile.getPath();
8287        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8288
8289        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8290            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8291
8292            // Some system apps still use directory structure for native libraries
8293            // in which case we might end up not detecting abi solely based on apk
8294            // structure. Try to detect abi based on directory structure.
8295            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8296                    pkg.applicationInfo.primaryCpuAbi == null) {
8297                setBundledAppAbisAndRoots(pkg, pkgSetting);
8298                setNativeLibraryPaths(pkg);
8299            }
8300
8301        } else {
8302            if ((scanFlags & SCAN_MOVE) != 0) {
8303                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8304                // but we already have this packages package info in the PackageSetting. We just
8305                // use that and derive the native library path based on the new codepath.
8306                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8307                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8308            }
8309
8310            // Set native library paths again. For moves, the path will be updated based on the
8311            // ABIs we've determined above. For non-moves, the path will be updated based on the
8312            // ABIs we determined during compilation, but the path will depend on the final
8313            // package path (after the rename away from the stage path).
8314            setNativeLibraryPaths(pkg);
8315        }
8316
8317        // This is a special case for the "system" package, where the ABI is
8318        // dictated by the zygote configuration (and init.rc). We should keep track
8319        // of this ABI so that we can deal with "normal" applications that run under
8320        // the same UID correctly.
8321        if (mPlatformPackage == pkg) {
8322            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8323                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8324        }
8325
8326        // If there's a mismatch between the abi-override in the package setting
8327        // and the abiOverride specified for the install. Warn about this because we
8328        // would've already compiled the app without taking the package setting into
8329        // account.
8330        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8331            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8332                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8333                        " for package " + pkg.packageName);
8334            }
8335        }
8336
8337        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8338        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8339        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8340
8341        // Copy the derived override back to the parsed package, so that we can
8342        // update the package settings accordingly.
8343        pkg.cpuAbiOverride = cpuAbiOverride;
8344
8345        if (DEBUG_ABI_SELECTION) {
8346            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8347                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8348                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8349        }
8350
8351        // Push the derived path down into PackageSettings so we know what to
8352        // clean up at uninstall time.
8353        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8354
8355        if (DEBUG_ABI_SELECTION) {
8356            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8357                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8358                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8359        }
8360
8361        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8362            // We don't do this here during boot because we can do it all
8363            // at once after scanning all existing packages.
8364            //
8365            // We also do this *before* we perform dexopt on this package, so that
8366            // we can avoid redundant dexopts, and also to make sure we've got the
8367            // code and package path correct.
8368            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8369                    pkg, true /* boot complete */);
8370        }
8371
8372        if (mFactoryTest && pkg.requestedPermissions.contains(
8373                android.Manifest.permission.FACTORY_TEST)) {
8374            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8375        }
8376
8377        ArrayList<PackageParser.Package> clientLibPkgs = null;
8378
8379        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8380            if (nonMutatedPs != null) {
8381                synchronized (mPackages) {
8382                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8383                }
8384            }
8385            return pkg;
8386        }
8387
8388        // Only privileged apps and updated privileged apps can add child packages.
8389        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8390            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8391                throw new PackageManagerException("Only privileged apps and updated "
8392                        + "privileged apps can add child packages. Ignoring package "
8393                        + pkg.packageName);
8394            }
8395            final int childCount = pkg.childPackages.size();
8396            for (int i = 0; i < childCount; i++) {
8397                PackageParser.Package childPkg = pkg.childPackages.get(i);
8398                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8399                        childPkg.packageName)) {
8400                    throw new PackageManagerException("Cannot override a child package of "
8401                            + "another disabled system app. Ignoring package " + pkg.packageName);
8402                }
8403            }
8404        }
8405
8406        // writer
8407        synchronized (mPackages) {
8408            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8409                // Only system apps can add new shared libraries.
8410                if (pkg.libraryNames != null) {
8411                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8412                        String name = pkg.libraryNames.get(i);
8413                        boolean allowed = false;
8414                        if (pkg.isUpdatedSystemApp()) {
8415                            // New library entries can only be added through the
8416                            // system image.  This is important to get rid of a lot
8417                            // of nasty edge cases: for example if we allowed a non-
8418                            // system update of the app to add a library, then uninstalling
8419                            // the update would make the library go away, and assumptions
8420                            // we made such as through app install filtering would now
8421                            // have allowed apps on the device which aren't compatible
8422                            // with it.  Better to just have the restriction here, be
8423                            // conservative, and create many fewer cases that can negatively
8424                            // impact the user experience.
8425                            final PackageSetting sysPs = mSettings
8426                                    .getDisabledSystemPkgLPr(pkg.packageName);
8427                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8428                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8429                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8430                                        allowed = true;
8431                                        break;
8432                                    }
8433                                }
8434                            }
8435                        } else {
8436                            allowed = true;
8437                        }
8438                        if (allowed) {
8439                            if (!mSharedLibraries.containsKey(name)) {
8440                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8441                            } else if (!name.equals(pkg.packageName)) {
8442                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8443                                        + name + " already exists; skipping");
8444                            }
8445                        } else {
8446                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8447                                    + name + " that is not declared on system image; skipping");
8448                        }
8449                    }
8450                    if ((scanFlags & SCAN_BOOTING) == 0) {
8451                        // If we are not booting, we need to update any applications
8452                        // that are clients of our shared library.  If we are booting,
8453                        // this will all be done once the scan is complete.
8454                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8455                    }
8456                }
8457            }
8458        }
8459
8460        if ((scanFlags & SCAN_BOOTING) != 0) {
8461            // No apps can run during boot scan, so they don't need to be frozen
8462        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8463            // Caller asked to not kill app, so it's probably not frozen
8464        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8465            // Caller asked us to ignore frozen check for some reason; they
8466            // probably didn't know the package name
8467        } else {
8468            // We're doing major surgery on this package, so it better be frozen
8469            // right now to keep it from launching
8470            checkPackageFrozen(pkgName);
8471        }
8472
8473        // Also need to kill any apps that are dependent on the library.
8474        if (clientLibPkgs != null) {
8475            for (int i=0; i<clientLibPkgs.size(); i++) {
8476                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8477                killApplication(clientPkg.applicationInfo.packageName,
8478                        clientPkg.applicationInfo.uid, "update lib");
8479            }
8480        }
8481
8482        // Make sure we're not adding any bogus keyset info
8483        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8484        ksms.assertScannedPackageValid(pkg);
8485
8486        // writer
8487        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8488
8489        boolean createIdmapFailed = false;
8490        synchronized (mPackages) {
8491            // We don't expect installation to fail beyond this point
8492
8493            if (pkgSetting.pkg != null) {
8494                // Note that |user| might be null during the initial boot scan. If a codePath
8495                // for an app has changed during a boot scan, it's due to an app update that's
8496                // part of the system partition and marker changes must be applied to all users.
8497                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8498                    (user != null) ? user : UserHandle.ALL);
8499            }
8500
8501            // Add the new setting to mSettings
8502            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8503            // Add the new setting to mPackages
8504            mPackages.put(pkg.applicationInfo.packageName, pkg);
8505            // Make sure we don't accidentally delete its data.
8506            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8507            while (iter.hasNext()) {
8508                PackageCleanItem item = iter.next();
8509                if (pkgName.equals(item.packageName)) {
8510                    iter.remove();
8511                }
8512            }
8513
8514            // Take care of first install / last update times.
8515            if (currentTime != 0) {
8516                if (pkgSetting.firstInstallTime == 0) {
8517                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8518                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8519                    pkgSetting.lastUpdateTime = currentTime;
8520                }
8521            } else if (pkgSetting.firstInstallTime == 0) {
8522                // We need *something*.  Take time time stamp of the file.
8523                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8524            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8525                if (scanFileTime != pkgSetting.timeStamp) {
8526                    // A package on the system image has changed; consider this
8527                    // to be an update.
8528                    pkgSetting.lastUpdateTime = scanFileTime;
8529                }
8530            }
8531
8532            // Add the package's KeySets to the global KeySetManagerService
8533            ksms.addScannedPackageLPw(pkg);
8534
8535            int N = pkg.providers.size();
8536            StringBuilder r = null;
8537            int i;
8538            for (i=0; i<N; i++) {
8539                PackageParser.Provider p = pkg.providers.get(i);
8540                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8541                        p.info.processName, pkg.applicationInfo.uid);
8542                mProviders.addProvider(p);
8543                p.syncable = p.info.isSyncable;
8544                if (p.info.authority != null) {
8545                    String names[] = p.info.authority.split(";");
8546                    p.info.authority = null;
8547                    for (int j = 0; j < names.length; j++) {
8548                        if (j == 1 && p.syncable) {
8549                            // We only want the first authority for a provider to possibly be
8550                            // syncable, so if we already added this provider using a different
8551                            // authority clear the syncable flag. We copy the provider before
8552                            // changing it because the mProviders object contains a reference
8553                            // to a provider that we don't want to change.
8554                            // Only do this for the second authority since the resulting provider
8555                            // object can be the same for all future authorities for this provider.
8556                            p = new PackageParser.Provider(p);
8557                            p.syncable = false;
8558                        }
8559                        if (!mProvidersByAuthority.containsKey(names[j])) {
8560                            mProvidersByAuthority.put(names[j], p);
8561                            if (p.info.authority == null) {
8562                                p.info.authority = names[j];
8563                            } else {
8564                                p.info.authority = p.info.authority + ";" + names[j];
8565                            }
8566                            if (DEBUG_PACKAGE_SCANNING) {
8567                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8568                                    Log.d(TAG, "Registered content provider: " + names[j]
8569                                            + ", className = " + p.info.name + ", isSyncable = "
8570                                            + p.info.isSyncable);
8571                            }
8572                        } else {
8573                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8574                            Slog.w(TAG, "Skipping provider name " + names[j] +
8575                                    " (in package " + pkg.applicationInfo.packageName +
8576                                    "): name already used by "
8577                                    + ((other != null && other.getComponentName() != null)
8578                                            ? other.getComponentName().getPackageName() : "?"));
8579                        }
8580                    }
8581                }
8582                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8583                    if (r == null) {
8584                        r = new StringBuilder(256);
8585                    } else {
8586                        r.append(' ');
8587                    }
8588                    r.append(p.info.name);
8589                }
8590            }
8591            if (r != null) {
8592                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8593            }
8594
8595            N = pkg.services.size();
8596            r = null;
8597            for (i=0; i<N; i++) {
8598                PackageParser.Service s = pkg.services.get(i);
8599                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8600                        s.info.processName, pkg.applicationInfo.uid);
8601                mServices.addService(s);
8602                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8603                    if (r == null) {
8604                        r = new StringBuilder(256);
8605                    } else {
8606                        r.append(' ');
8607                    }
8608                    r.append(s.info.name);
8609                }
8610            }
8611            if (r != null) {
8612                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8613            }
8614
8615            N = pkg.receivers.size();
8616            r = null;
8617            for (i=0; i<N; i++) {
8618                PackageParser.Activity a = pkg.receivers.get(i);
8619                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8620                        a.info.processName, pkg.applicationInfo.uid);
8621                mReceivers.addActivity(a, "receiver");
8622                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8623                    if (r == null) {
8624                        r = new StringBuilder(256);
8625                    } else {
8626                        r.append(' ');
8627                    }
8628                    r.append(a.info.name);
8629                }
8630            }
8631            if (r != null) {
8632                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8633            }
8634
8635            N = pkg.activities.size();
8636            r = null;
8637            for (i=0; i<N; i++) {
8638                PackageParser.Activity a = pkg.activities.get(i);
8639                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8640                        a.info.processName, pkg.applicationInfo.uid);
8641                mActivities.addActivity(a, "activity");
8642                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8643                    if (r == null) {
8644                        r = new StringBuilder(256);
8645                    } else {
8646                        r.append(' ');
8647                    }
8648                    r.append(a.info.name);
8649                }
8650            }
8651            if (r != null) {
8652                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8653            }
8654
8655            N = pkg.permissionGroups.size();
8656            r = null;
8657            for (i=0; i<N; i++) {
8658                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8659                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8660                if (cur == null) {
8661                    mPermissionGroups.put(pg.info.name, pg);
8662                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8663                        if (r == null) {
8664                            r = new StringBuilder(256);
8665                        } else {
8666                            r.append(' ');
8667                        }
8668                        r.append(pg.info.name);
8669                    }
8670                } else {
8671                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8672                            + pg.info.packageName + " ignored: original from "
8673                            + cur.info.packageName);
8674                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8675                        if (r == null) {
8676                            r = new StringBuilder(256);
8677                        } else {
8678                            r.append(' ');
8679                        }
8680                        r.append("DUP:");
8681                        r.append(pg.info.name);
8682                    }
8683                }
8684            }
8685            if (r != null) {
8686                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8687            }
8688
8689            N = pkg.permissions.size();
8690            r = null;
8691            for (i=0; i<N; i++) {
8692                PackageParser.Permission p = pkg.permissions.get(i);
8693
8694                // Assume by default that we did not install this permission into the system.
8695                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8696
8697                // Now that permission groups have a special meaning, we ignore permission
8698                // groups for legacy apps to prevent unexpected behavior. In particular,
8699                // permissions for one app being granted to someone just becase they happen
8700                // to be in a group defined by another app (before this had no implications).
8701                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8702                    p.group = mPermissionGroups.get(p.info.group);
8703                    // Warn for a permission in an unknown group.
8704                    if (p.info.group != null && p.group == null) {
8705                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8706                                + p.info.packageName + " in an unknown group " + p.info.group);
8707                    }
8708                }
8709
8710                ArrayMap<String, BasePermission> permissionMap =
8711                        p.tree ? mSettings.mPermissionTrees
8712                                : mSettings.mPermissions;
8713                BasePermission bp = permissionMap.get(p.info.name);
8714
8715                // Allow system apps to redefine non-system permissions
8716                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8717                    final boolean currentOwnerIsSystem = (bp.perm != null
8718                            && isSystemApp(bp.perm.owner));
8719                    if (isSystemApp(p.owner)) {
8720                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8721                            // It's a built-in permission and no owner, take ownership now
8722                            bp.packageSetting = pkgSetting;
8723                            bp.perm = p;
8724                            bp.uid = pkg.applicationInfo.uid;
8725                            bp.sourcePackage = p.info.packageName;
8726                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8727                        } else if (!currentOwnerIsSystem) {
8728                            String msg = "New decl " + p.owner + " of permission  "
8729                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8730                            reportSettingsProblem(Log.WARN, msg);
8731                            bp = null;
8732                        }
8733                    }
8734                }
8735
8736                if (bp == null) {
8737                    bp = new BasePermission(p.info.name, p.info.packageName,
8738                            BasePermission.TYPE_NORMAL);
8739                    permissionMap.put(p.info.name, bp);
8740                }
8741
8742                if (bp.perm == null) {
8743                    if (bp.sourcePackage == null
8744                            || bp.sourcePackage.equals(p.info.packageName)) {
8745                        BasePermission tree = findPermissionTreeLP(p.info.name);
8746                        if (tree == null
8747                                || tree.sourcePackage.equals(p.info.packageName)) {
8748                            bp.packageSetting = pkgSetting;
8749                            bp.perm = p;
8750                            bp.uid = pkg.applicationInfo.uid;
8751                            bp.sourcePackage = p.info.packageName;
8752                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8753                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8754                                if (r == null) {
8755                                    r = new StringBuilder(256);
8756                                } else {
8757                                    r.append(' ');
8758                                }
8759                                r.append(p.info.name);
8760                            }
8761                        } else {
8762                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8763                                    + p.info.packageName + " ignored: base tree "
8764                                    + tree.name + " is from package "
8765                                    + tree.sourcePackage);
8766                        }
8767                    } else {
8768                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8769                                + p.info.packageName + " ignored: original from "
8770                                + bp.sourcePackage);
8771                    }
8772                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8773                    if (r == null) {
8774                        r = new StringBuilder(256);
8775                    } else {
8776                        r.append(' ');
8777                    }
8778                    r.append("DUP:");
8779                    r.append(p.info.name);
8780                }
8781                if (bp.perm == p) {
8782                    bp.protectionLevel = p.info.protectionLevel;
8783                }
8784            }
8785
8786            if (r != null) {
8787                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8788            }
8789
8790            N = pkg.instrumentation.size();
8791            r = null;
8792            for (i=0; i<N; i++) {
8793                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8794                a.info.packageName = pkg.applicationInfo.packageName;
8795                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8796                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8797                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8798                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8799                a.info.dataDir = pkg.applicationInfo.dataDir;
8800                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8801                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8802
8803                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8804                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8805                mInstrumentation.put(a.getComponentName(), a);
8806                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8807                    if (r == null) {
8808                        r = new StringBuilder(256);
8809                    } else {
8810                        r.append(' ');
8811                    }
8812                    r.append(a.info.name);
8813                }
8814            }
8815            if (r != null) {
8816                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8817            }
8818
8819            if (pkg.protectedBroadcasts != null) {
8820                N = pkg.protectedBroadcasts.size();
8821                for (i=0; i<N; i++) {
8822                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8823                }
8824            }
8825
8826            pkgSetting.setTimeStamp(scanFileTime);
8827
8828            // Create idmap files for pairs of (packages, overlay packages).
8829            // Note: "android", ie framework-res.apk, is handled by native layers.
8830            if (pkg.mOverlayTarget != null) {
8831                // This is an overlay package.
8832                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8833                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8834                        mOverlays.put(pkg.mOverlayTarget,
8835                                new ArrayMap<String, PackageParser.Package>());
8836                    }
8837                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8838                    map.put(pkg.packageName, pkg);
8839                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8840                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8841                        createIdmapFailed = true;
8842                    }
8843                }
8844            } else if (mOverlays.containsKey(pkg.packageName) &&
8845                    !pkg.packageName.equals("android")) {
8846                // This is a regular package, with one or more known overlay packages.
8847                createIdmapsForPackageLI(pkg);
8848            }
8849        }
8850
8851        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8852
8853        if (createIdmapFailed) {
8854            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8855                    "scanPackageLI failed to createIdmap");
8856        }
8857        return pkg;
8858    }
8859
8860    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
8861            PackageParser.Package update, UserHandle user) {
8862        if (existing.applicationInfo == null || update.applicationInfo == null) {
8863            // This isn't due to an app installation.
8864            return;
8865        }
8866
8867        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
8868        final File newCodePath = new File(update.applicationInfo.getCodePath());
8869
8870        // The codePath hasn't changed, so there's nothing for us to do.
8871        if (Objects.equals(oldCodePath, newCodePath)) {
8872            return;
8873        }
8874
8875        File canonicalNewCodePath;
8876        try {
8877            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
8878        } catch (IOException e) {
8879            Slog.w(TAG, "Failed to get canonical path.", e);
8880            return;
8881        }
8882
8883        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
8884        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
8885        // that the last component of the path (i.e, the name) doesn't need canonicalization
8886        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
8887        // but may change in the future. Hopefully this function won't exist at that point.
8888        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
8889                oldCodePath.getName());
8890
8891        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
8892        // with "@".
8893        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
8894        if (!oldMarkerPrefix.endsWith("@")) {
8895            oldMarkerPrefix += "@";
8896        }
8897        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
8898        if (!newMarkerPrefix.endsWith("@")) {
8899            newMarkerPrefix += "@";
8900        }
8901
8902        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
8903        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
8904        for (String updatedPath : updatedPaths) {
8905            String updatedPathName = new File(updatedPath).getName();
8906            markerSuffixes.add(updatedPathName.replace('/', '@'));
8907        }
8908
8909        for (int userId : resolveUserIds(user.getIdentifier())) {
8910            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
8911
8912            for (String markerSuffix : markerSuffixes) {
8913                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
8914                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
8915                if (oldForeignUseMark.exists()) {
8916                    try {
8917                        Os.rename(oldForeignUseMark.getAbsolutePath(),
8918                                newForeignUseMark.getAbsolutePath());
8919                    } catch (ErrnoException e) {
8920                        Slog.w(TAG, "Failed to rename foreign use marker", e);
8921                        oldForeignUseMark.delete();
8922                    }
8923                }
8924            }
8925        }
8926    }
8927
8928    /**
8929     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8930     * is derived purely on the basis of the contents of {@code scanFile} and
8931     * {@code cpuAbiOverride}.
8932     *
8933     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8934     */
8935    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8936                                 String cpuAbiOverride, boolean extractLibs)
8937            throws PackageManagerException {
8938        // TODO: We can probably be smarter about this stuff. For installed apps,
8939        // we can calculate this information at install time once and for all. For
8940        // system apps, we can probably assume that this information doesn't change
8941        // after the first boot scan. As things stand, we do lots of unnecessary work.
8942
8943        // Give ourselves some initial paths; we'll come back for another
8944        // pass once we've determined ABI below.
8945        setNativeLibraryPaths(pkg);
8946
8947        // We would never need to extract libs for forward-locked and external packages,
8948        // since the container service will do it for us. We shouldn't attempt to
8949        // extract libs from system app when it was not updated.
8950        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8951                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8952            extractLibs = false;
8953        }
8954
8955        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8956        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8957
8958        NativeLibraryHelper.Handle handle = null;
8959        try {
8960            handle = NativeLibraryHelper.Handle.create(pkg);
8961            // TODO(multiArch): This can be null for apps that didn't go through the
8962            // usual installation process. We can calculate it again, like we
8963            // do during install time.
8964            //
8965            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8966            // unnecessary.
8967            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8968
8969            // Null out the abis so that they can be recalculated.
8970            pkg.applicationInfo.primaryCpuAbi = null;
8971            pkg.applicationInfo.secondaryCpuAbi = null;
8972            if (isMultiArch(pkg.applicationInfo)) {
8973                // Warn if we've set an abiOverride for multi-lib packages..
8974                // By definition, we need to copy both 32 and 64 bit libraries for
8975                // such packages.
8976                if (pkg.cpuAbiOverride != null
8977                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8978                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8979                }
8980
8981                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8982                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8983                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8984                    if (extractLibs) {
8985                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8986                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8987                                useIsaSpecificSubdirs);
8988                    } else {
8989                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8990                    }
8991                }
8992
8993                maybeThrowExceptionForMultiArchCopy(
8994                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8995
8996                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8997                    if (extractLibs) {
8998                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8999                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9000                                useIsaSpecificSubdirs);
9001                    } else {
9002                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9003                    }
9004                }
9005
9006                maybeThrowExceptionForMultiArchCopy(
9007                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9008
9009                if (abi64 >= 0) {
9010                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9011                }
9012
9013                if (abi32 >= 0) {
9014                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9015                    if (abi64 >= 0) {
9016                        if (pkg.use32bitAbi) {
9017                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9018                            pkg.applicationInfo.primaryCpuAbi = abi;
9019                        } else {
9020                            pkg.applicationInfo.secondaryCpuAbi = abi;
9021                        }
9022                    } else {
9023                        pkg.applicationInfo.primaryCpuAbi = abi;
9024                    }
9025                }
9026
9027            } else {
9028                String[] abiList = (cpuAbiOverride != null) ?
9029                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9030
9031                // Enable gross and lame hacks for apps that are built with old
9032                // SDK tools. We must scan their APKs for renderscript bitcode and
9033                // not launch them if it's present. Don't bother checking on devices
9034                // that don't have 64 bit support.
9035                boolean needsRenderScriptOverride = false;
9036                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9037                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9038                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9039                    needsRenderScriptOverride = true;
9040                }
9041
9042                final int copyRet;
9043                if (extractLibs) {
9044                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9045                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9046                } else {
9047                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9048                }
9049
9050                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9051                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9052                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9053                }
9054
9055                if (copyRet >= 0) {
9056                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9057                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9058                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9059                } else if (needsRenderScriptOverride) {
9060                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9061                }
9062            }
9063        } catch (IOException ioe) {
9064            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9065        } finally {
9066            IoUtils.closeQuietly(handle);
9067        }
9068
9069        // Now that we've calculated the ABIs and determined if it's an internal app,
9070        // we will go ahead and populate the nativeLibraryPath.
9071        setNativeLibraryPaths(pkg);
9072    }
9073
9074    /**
9075     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9076     * i.e, so that all packages can be run inside a single process if required.
9077     *
9078     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9079     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9080     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9081     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9082     * updating a package that belongs to a shared user.
9083     *
9084     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9085     * adds unnecessary complexity.
9086     */
9087    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9088            PackageParser.Package scannedPackage, boolean bootComplete) {
9089        String requiredInstructionSet = null;
9090        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9091            requiredInstructionSet = VMRuntime.getInstructionSet(
9092                     scannedPackage.applicationInfo.primaryCpuAbi);
9093        }
9094
9095        PackageSetting requirer = null;
9096        for (PackageSetting ps : packagesForUser) {
9097            // If packagesForUser contains scannedPackage, we skip it. This will happen
9098            // when scannedPackage is an update of an existing package. Without this check,
9099            // we will never be able to change the ABI of any package belonging to a shared
9100            // user, even if it's compatible with other packages.
9101            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9102                if (ps.primaryCpuAbiString == null) {
9103                    continue;
9104                }
9105
9106                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9107                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9108                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9109                    // this but there's not much we can do.
9110                    String errorMessage = "Instruction set mismatch, "
9111                            + ((requirer == null) ? "[caller]" : requirer)
9112                            + " requires " + requiredInstructionSet + " whereas " + ps
9113                            + " requires " + instructionSet;
9114                    Slog.w(TAG, errorMessage);
9115                }
9116
9117                if (requiredInstructionSet == null) {
9118                    requiredInstructionSet = instructionSet;
9119                    requirer = ps;
9120                }
9121            }
9122        }
9123
9124        if (requiredInstructionSet != null) {
9125            String adjustedAbi;
9126            if (requirer != null) {
9127                // requirer != null implies that either scannedPackage was null or that scannedPackage
9128                // did not require an ABI, in which case we have to adjust scannedPackage to match
9129                // the ABI of the set (which is the same as requirer's ABI)
9130                adjustedAbi = requirer.primaryCpuAbiString;
9131                if (scannedPackage != null) {
9132                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9133                }
9134            } else {
9135                // requirer == null implies that we're updating all ABIs in the set to
9136                // match scannedPackage.
9137                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9138            }
9139
9140            for (PackageSetting ps : packagesForUser) {
9141                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9142                    if (ps.primaryCpuAbiString != null) {
9143                        continue;
9144                    }
9145
9146                    ps.primaryCpuAbiString = adjustedAbi;
9147                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9148                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9149                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9150                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9151                                + " (requirer="
9152                                + (requirer == null ? "null" : requirer.pkg.packageName)
9153                                + ", scannedPackage="
9154                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9155                                + ")");
9156                        try {
9157                            mInstaller.rmdex(ps.codePathString,
9158                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9159                        } catch (InstallerException ignored) {
9160                        }
9161                    }
9162                }
9163            }
9164        }
9165    }
9166
9167    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9168        synchronized (mPackages) {
9169            mResolverReplaced = true;
9170            // Set up information for custom user intent resolution activity.
9171            mResolveActivity.applicationInfo = pkg.applicationInfo;
9172            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9173            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9174            mResolveActivity.processName = pkg.applicationInfo.packageName;
9175            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9176            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9177                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9178            mResolveActivity.theme = 0;
9179            mResolveActivity.exported = true;
9180            mResolveActivity.enabled = true;
9181            mResolveInfo.activityInfo = mResolveActivity;
9182            mResolveInfo.priority = 0;
9183            mResolveInfo.preferredOrder = 0;
9184            mResolveInfo.match = 0;
9185            mResolveComponentName = mCustomResolverComponentName;
9186            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9187                    mResolveComponentName);
9188        }
9189    }
9190
9191    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9192        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9193
9194        // Set up information for ephemeral installer activity
9195        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9196        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9197        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9198        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9199        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9200        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9201                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9202        mEphemeralInstallerActivity.theme = 0;
9203        mEphemeralInstallerActivity.exported = true;
9204        mEphemeralInstallerActivity.enabled = true;
9205        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9206        mEphemeralInstallerInfo.priority = 0;
9207        mEphemeralInstallerInfo.preferredOrder = 0;
9208        mEphemeralInstallerInfo.match = 0;
9209
9210        if (DEBUG_EPHEMERAL) {
9211            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9212        }
9213    }
9214
9215    private static String calculateBundledApkRoot(final String codePathString) {
9216        final File codePath = new File(codePathString);
9217        final File codeRoot;
9218        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9219            codeRoot = Environment.getRootDirectory();
9220        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9221            codeRoot = Environment.getOemDirectory();
9222        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9223            codeRoot = Environment.getVendorDirectory();
9224        } else {
9225            // Unrecognized code path; take its top real segment as the apk root:
9226            // e.g. /something/app/blah.apk => /something
9227            try {
9228                File f = codePath.getCanonicalFile();
9229                File parent = f.getParentFile();    // non-null because codePath is a file
9230                File tmp;
9231                while ((tmp = parent.getParentFile()) != null) {
9232                    f = parent;
9233                    parent = tmp;
9234                }
9235                codeRoot = f;
9236                Slog.w(TAG, "Unrecognized code path "
9237                        + codePath + " - using " + codeRoot);
9238            } catch (IOException e) {
9239                // Can't canonicalize the code path -- shenanigans?
9240                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9241                return Environment.getRootDirectory().getPath();
9242            }
9243        }
9244        return codeRoot.getPath();
9245    }
9246
9247    /**
9248     * Derive and set the location of native libraries for the given package,
9249     * which varies depending on where and how the package was installed.
9250     */
9251    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9252        final ApplicationInfo info = pkg.applicationInfo;
9253        final String codePath = pkg.codePath;
9254        final File codeFile = new File(codePath);
9255        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9256        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9257
9258        info.nativeLibraryRootDir = null;
9259        info.nativeLibraryRootRequiresIsa = false;
9260        info.nativeLibraryDir = null;
9261        info.secondaryNativeLibraryDir = null;
9262
9263        if (isApkFile(codeFile)) {
9264            // Monolithic install
9265            if (bundledApp) {
9266                // If "/system/lib64/apkname" exists, assume that is the per-package
9267                // native library directory to use; otherwise use "/system/lib/apkname".
9268                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9269                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9270                        getPrimaryInstructionSet(info));
9271
9272                // This is a bundled system app so choose the path based on the ABI.
9273                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9274                // is just the default path.
9275                final String apkName = deriveCodePathName(codePath);
9276                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9277                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9278                        apkName).getAbsolutePath();
9279
9280                if (info.secondaryCpuAbi != null) {
9281                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9282                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9283                            secondaryLibDir, apkName).getAbsolutePath();
9284                }
9285            } else if (asecApp) {
9286                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9287                        .getAbsolutePath();
9288            } else {
9289                final String apkName = deriveCodePathName(codePath);
9290                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9291                        .getAbsolutePath();
9292            }
9293
9294            info.nativeLibraryRootRequiresIsa = false;
9295            info.nativeLibraryDir = info.nativeLibraryRootDir;
9296        } else {
9297            // Cluster install
9298            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9299            info.nativeLibraryRootRequiresIsa = true;
9300
9301            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9302                    getPrimaryInstructionSet(info)).getAbsolutePath();
9303
9304            if (info.secondaryCpuAbi != null) {
9305                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9306                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9307            }
9308        }
9309    }
9310
9311    /**
9312     * Calculate the abis and roots for a bundled app. These can uniquely
9313     * be determined from the contents of the system partition, i.e whether
9314     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9315     * of this information, and instead assume that the system was built
9316     * sensibly.
9317     */
9318    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9319                                           PackageSetting pkgSetting) {
9320        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9321
9322        // If "/system/lib64/apkname" exists, assume that is the per-package
9323        // native library directory to use; otherwise use "/system/lib/apkname".
9324        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9325        setBundledAppAbi(pkg, apkRoot, apkName);
9326        // pkgSetting might be null during rescan following uninstall of updates
9327        // to a bundled app, so accommodate that possibility.  The settings in
9328        // that case will be established later from the parsed package.
9329        //
9330        // If the settings aren't null, sync them up with what we've just derived.
9331        // note that apkRoot isn't stored in the package settings.
9332        if (pkgSetting != null) {
9333            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9334            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9335        }
9336    }
9337
9338    /**
9339     * Deduces the ABI of a bundled app and sets the relevant fields on the
9340     * parsed pkg object.
9341     *
9342     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9343     *        under which system libraries are installed.
9344     * @param apkName the name of the installed package.
9345     */
9346    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9347        final File codeFile = new File(pkg.codePath);
9348
9349        final boolean has64BitLibs;
9350        final boolean has32BitLibs;
9351        if (isApkFile(codeFile)) {
9352            // Monolithic install
9353            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9354            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9355        } else {
9356            // Cluster install
9357            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9358            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9359                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9360                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9361                has64BitLibs = (new File(rootDir, isa)).exists();
9362            } else {
9363                has64BitLibs = false;
9364            }
9365            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9366                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9367                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9368                has32BitLibs = (new File(rootDir, isa)).exists();
9369            } else {
9370                has32BitLibs = false;
9371            }
9372        }
9373
9374        if (has64BitLibs && !has32BitLibs) {
9375            // The package has 64 bit libs, but not 32 bit libs. Its primary
9376            // ABI should be 64 bit. We can safely assume here that the bundled
9377            // native libraries correspond to the most preferred ABI in the list.
9378
9379            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9380            pkg.applicationInfo.secondaryCpuAbi = null;
9381        } else if (has32BitLibs && !has64BitLibs) {
9382            // The package has 32 bit libs but not 64 bit libs. Its primary
9383            // ABI should be 32 bit.
9384
9385            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9386            pkg.applicationInfo.secondaryCpuAbi = null;
9387        } else if (has32BitLibs && has64BitLibs) {
9388            // The application has both 64 and 32 bit bundled libraries. We check
9389            // here that the app declares multiArch support, and warn if it doesn't.
9390            //
9391            // We will be lenient here and record both ABIs. The primary will be the
9392            // ABI that's higher on the list, i.e, a device that's configured to prefer
9393            // 64 bit apps will see a 64 bit primary ABI,
9394
9395            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9396                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9397            }
9398
9399            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9400                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9401                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9402            } else {
9403                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9404                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9405            }
9406        } else {
9407            pkg.applicationInfo.primaryCpuAbi = null;
9408            pkg.applicationInfo.secondaryCpuAbi = null;
9409        }
9410    }
9411
9412    private void killApplication(String pkgName, int appId, String reason) {
9413        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9414    }
9415
9416    private void killApplication(String pkgName, int appId, int userId, String reason) {
9417        // Request the ActivityManager to kill the process(only for existing packages)
9418        // so that we do not end up in a confused state while the user is still using the older
9419        // version of the application while the new one gets installed.
9420        final long token = Binder.clearCallingIdentity();
9421        try {
9422            IActivityManager am = ActivityManagerNative.getDefault();
9423            if (am != null) {
9424                try {
9425                    am.killApplication(pkgName, appId, userId, reason);
9426                } catch (RemoteException e) {
9427                }
9428            }
9429        } finally {
9430            Binder.restoreCallingIdentity(token);
9431        }
9432    }
9433
9434    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9435        // Remove the parent package setting
9436        PackageSetting ps = (PackageSetting) pkg.mExtras;
9437        if (ps != null) {
9438            removePackageLI(ps, chatty);
9439        }
9440        // Remove the child package setting
9441        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9442        for (int i = 0; i < childCount; i++) {
9443            PackageParser.Package childPkg = pkg.childPackages.get(i);
9444            ps = (PackageSetting) childPkg.mExtras;
9445            if (ps != null) {
9446                removePackageLI(ps, chatty);
9447            }
9448        }
9449    }
9450
9451    void removePackageLI(PackageSetting ps, boolean chatty) {
9452        if (DEBUG_INSTALL) {
9453            if (chatty)
9454                Log.d(TAG, "Removing package " + ps.name);
9455        }
9456
9457        // writer
9458        synchronized (mPackages) {
9459            mPackages.remove(ps.name);
9460            final PackageParser.Package pkg = ps.pkg;
9461            if (pkg != null) {
9462                cleanPackageDataStructuresLILPw(pkg, chatty);
9463            }
9464        }
9465    }
9466
9467    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9468        if (DEBUG_INSTALL) {
9469            if (chatty)
9470                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9471        }
9472
9473        // writer
9474        synchronized (mPackages) {
9475            // Remove the parent package
9476            mPackages.remove(pkg.applicationInfo.packageName);
9477            cleanPackageDataStructuresLILPw(pkg, chatty);
9478
9479            // Remove the child packages
9480            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9481            for (int i = 0; i < childCount; i++) {
9482                PackageParser.Package childPkg = pkg.childPackages.get(i);
9483                mPackages.remove(childPkg.applicationInfo.packageName);
9484                cleanPackageDataStructuresLILPw(childPkg, chatty);
9485            }
9486        }
9487    }
9488
9489    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9490        int N = pkg.providers.size();
9491        StringBuilder r = null;
9492        int i;
9493        for (i=0; i<N; i++) {
9494            PackageParser.Provider p = pkg.providers.get(i);
9495            mProviders.removeProvider(p);
9496            if (p.info.authority == null) {
9497
9498                /* There was another ContentProvider with this authority when
9499                 * this app was installed so this authority is null,
9500                 * Ignore it as we don't have to unregister the provider.
9501                 */
9502                continue;
9503            }
9504            String names[] = p.info.authority.split(";");
9505            for (int j = 0; j < names.length; j++) {
9506                if (mProvidersByAuthority.get(names[j]) == p) {
9507                    mProvidersByAuthority.remove(names[j]);
9508                    if (DEBUG_REMOVE) {
9509                        if (chatty)
9510                            Log.d(TAG, "Unregistered content provider: " + names[j]
9511                                    + ", className = " + p.info.name + ", isSyncable = "
9512                                    + p.info.isSyncable);
9513                    }
9514                }
9515            }
9516            if (DEBUG_REMOVE && chatty) {
9517                if (r == null) {
9518                    r = new StringBuilder(256);
9519                } else {
9520                    r.append(' ');
9521                }
9522                r.append(p.info.name);
9523            }
9524        }
9525        if (r != null) {
9526            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9527        }
9528
9529        N = pkg.services.size();
9530        r = null;
9531        for (i=0; i<N; i++) {
9532            PackageParser.Service s = pkg.services.get(i);
9533            mServices.removeService(s);
9534            if (chatty) {
9535                if (r == null) {
9536                    r = new StringBuilder(256);
9537                } else {
9538                    r.append(' ');
9539                }
9540                r.append(s.info.name);
9541            }
9542        }
9543        if (r != null) {
9544            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9545        }
9546
9547        N = pkg.receivers.size();
9548        r = null;
9549        for (i=0; i<N; i++) {
9550            PackageParser.Activity a = pkg.receivers.get(i);
9551            mReceivers.removeActivity(a, "receiver");
9552            if (DEBUG_REMOVE && chatty) {
9553                if (r == null) {
9554                    r = new StringBuilder(256);
9555                } else {
9556                    r.append(' ');
9557                }
9558                r.append(a.info.name);
9559            }
9560        }
9561        if (r != null) {
9562            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9563        }
9564
9565        N = pkg.activities.size();
9566        r = null;
9567        for (i=0; i<N; i++) {
9568            PackageParser.Activity a = pkg.activities.get(i);
9569            mActivities.removeActivity(a, "activity");
9570            if (DEBUG_REMOVE && chatty) {
9571                if (r == null) {
9572                    r = new StringBuilder(256);
9573                } else {
9574                    r.append(' ');
9575                }
9576                r.append(a.info.name);
9577            }
9578        }
9579        if (r != null) {
9580            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9581        }
9582
9583        N = pkg.permissions.size();
9584        r = null;
9585        for (i=0; i<N; i++) {
9586            PackageParser.Permission p = pkg.permissions.get(i);
9587            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9588            if (bp == null) {
9589                bp = mSettings.mPermissionTrees.get(p.info.name);
9590            }
9591            if (bp != null && bp.perm == p) {
9592                bp.perm = null;
9593                if (DEBUG_REMOVE && chatty) {
9594                    if (r == null) {
9595                        r = new StringBuilder(256);
9596                    } else {
9597                        r.append(' ');
9598                    }
9599                    r.append(p.info.name);
9600                }
9601            }
9602            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9603                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9604                if (appOpPkgs != null) {
9605                    appOpPkgs.remove(pkg.packageName);
9606                }
9607            }
9608        }
9609        if (r != null) {
9610            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9611        }
9612
9613        N = pkg.requestedPermissions.size();
9614        r = null;
9615        for (i=0; i<N; i++) {
9616            String perm = pkg.requestedPermissions.get(i);
9617            BasePermission bp = mSettings.mPermissions.get(perm);
9618            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9619                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9620                if (appOpPkgs != null) {
9621                    appOpPkgs.remove(pkg.packageName);
9622                    if (appOpPkgs.isEmpty()) {
9623                        mAppOpPermissionPackages.remove(perm);
9624                    }
9625                }
9626            }
9627        }
9628        if (r != null) {
9629            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9630        }
9631
9632        N = pkg.instrumentation.size();
9633        r = null;
9634        for (i=0; i<N; i++) {
9635            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9636            mInstrumentation.remove(a.getComponentName());
9637            if (DEBUG_REMOVE && chatty) {
9638                if (r == null) {
9639                    r = new StringBuilder(256);
9640                } else {
9641                    r.append(' ');
9642                }
9643                r.append(a.info.name);
9644            }
9645        }
9646        if (r != null) {
9647            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9648        }
9649
9650        r = null;
9651        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9652            // Only system apps can hold shared libraries.
9653            if (pkg.libraryNames != null) {
9654                for (i=0; i<pkg.libraryNames.size(); i++) {
9655                    String name = pkg.libraryNames.get(i);
9656                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9657                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9658                        mSharedLibraries.remove(name);
9659                        if (DEBUG_REMOVE && chatty) {
9660                            if (r == null) {
9661                                r = new StringBuilder(256);
9662                            } else {
9663                                r.append(' ');
9664                            }
9665                            r.append(name);
9666                        }
9667                    }
9668                }
9669            }
9670        }
9671        if (r != null) {
9672            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9673        }
9674    }
9675
9676    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9677        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9678            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9679                return true;
9680            }
9681        }
9682        return false;
9683    }
9684
9685    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9686    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9687    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9688
9689    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9690        // Update the parent permissions
9691        updatePermissionsLPw(pkg.packageName, pkg, flags);
9692        // Update the child permissions
9693        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9694        for (int i = 0; i < childCount; i++) {
9695            PackageParser.Package childPkg = pkg.childPackages.get(i);
9696            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9697        }
9698    }
9699
9700    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9701            int flags) {
9702        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9703        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9704    }
9705
9706    private void updatePermissionsLPw(String changingPkg,
9707            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9708        // Make sure there are no dangling permission trees.
9709        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9710        while (it.hasNext()) {
9711            final BasePermission bp = it.next();
9712            if (bp.packageSetting == null) {
9713                // We may not yet have parsed the package, so just see if
9714                // we still know about its settings.
9715                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9716            }
9717            if (bp.packageSetting == null) {
9718                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9719                        + " from package " + bp.sourcePackage);
9720                it.remove();
9721            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9722                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9723                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9724                            + " from package " + bp.sourcePackage);
9725                    flags |= UPDATE_PERMISSIONS_ALL;
9726                    it.remove();
9727                }
9728            }
9729        }
9730
9731        // Make sure all dynamic permissions have been assigned to a package,
9732        // and make sure there are no dangling permissions.
9733        it = mSettings.mPermissions.values().iterator();
9734        while (it.hasNext()) {
9735            final BasePermission bp = it.next();
9736            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9737                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9738                        + bp.name + " pkg=" + bp.sourcePackage
9739                        + " info=" + bp.pendingInfo);
9740                if (bp.packageSetting == null && bp.pendingInfo != null) {
9741                    final BasePermission tree = findPermissionTreeLP(bp.name);
9742                    if (tree != null && tree.perm != null) {
9743                        bp.packageSetting = tree.packageSetting;
9744                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9745                                new PermissionInfo(bp.pendingInfo));
9746                        bp.perm.info.packageName = tree.perm.info.packageName;
9747                        bp.perm.info.name = bp.name;
9748                        bp.uid = tree.uid;
9749                    }
9750                }
9751            }
9752            if (bp.packageSetting == null) {
9753                // We may not yet have parsed the package, so just see if
9754                // we still know about its settings.
9755                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9756            }
9757            if (bp.packageSetting == null) {
9758                Slog.w(TAG, "Removing dangling permission: " + bp.name
9759                        + " from package " + bp.sourcePackage);
9760                it.remove();
9761            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9762                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9763                    Slog.i(TAG, "Removing old permission: " + bp.name
9764                            + " from package " + bp.sourcePackage);
9765                    flags |= UPDATE_PERMISSIONS_ALL;
9766                    it.remove();
9767                }
9768            }
9769        }
9770
9771        // Now update the permissions for all packages, in particular
9772        // replace the granted permissions of the system packages.
9773        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9774            for (PackageParser.Package pkg : mPackages.values()) {
9775                if (pkg != pkgInfo) {
9776                    // Only replace for packages on requested volume
9777                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9778                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9779                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9780                    grantPermissionsLPw(pkg, replace, changingPkg);
9781                }
9782            }
9783        }
9784
9785        if (pkgInfo != null) {
9786            // Only replace for packages on requested volume
9787            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9788            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9789                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9790            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9791        }
9792    }
9793
9794    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9795            String packageOfInterest) {
9796        // IMPORTANT: There are two types of permissions: install and runtime.
9797        // Install time permissions are granted when the app is installed to
9798        // all device users and users added in the future. Runtime permissions
9799        // are granted at runtime explicitly to specific users. Normal and signature
9800        // protected permissions are install time permissions. Dangerous permissions
9801        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9802        // otherwise they are runtime permissions. This function does not manage
9803        // runtime permissions except for the case an app targeting Lollipop MR1
9804        // being upgraded to target a newer SDK, in which case dangerous permissions
9805        // are transformed from install time to runtime ones.
9806
9807        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9808        if (ps == null) {
9809            return;
9810        }
9811
9812        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9813
9814        PermissionsState permissionsState = ps.getPermissionsState();
9815        PermissionsState origPermissions = permissionsState;
9816
9817        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9818
9819        boolean runtimePermissionsRevoked = false;
9820        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9821
9822        boolean changedInstallPermission = false;
9823
9824        if (replace) {
9825            ps.installPermissionsFixed = false;
9826            if (!ps.isSharedUser()) {
9827                origPermissions = new PermissionsState(permissionsState);
9828                permissionsState.reset();
9829            } else {
9830                // We need to know only about runtime permission changes since the
9831                // calling code always writes the install permissions state but
9832                // the runtime ones are written only if changed. The only cases of
9833                // changed runtime permissions here are promotion of an install to
9834                // runtime and revocation of a runtime from a shared user.
9835                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9836                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9837                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9838                    runtimePermissionsRevoked = true;
9839                }
9840            }
9841        }
9842
9843        permissionsState.setGlobalGids(mGlobalGids);
9844
9845        final int N = pkg.requestedPermissions.size();
9846        for (int i=0; i<N; i++) {
9847            final String name = pkg.requestedPermissions.get(i);
9848            final BasePermission bp = mSettings.mPermissions.get(name);
9849
9850            if (DEBUG_INSTALL) {
9851                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9852            }
9853
9854            if (bp == null || bp.packageSetting == null) {
9855                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9856                    Slog.w(TAG, "Unknown permission " + name
9857                            + " in package " + pkg.packageName);
9858                }
9859                continue;
9860            }
9861
9862            final String perm = bp.name;
9863            boolean allowedSig = false;
9864            int grant = GRANT_DENIED;
9865
9866            // Keep track of app op permissions.
9867            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9868                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9869                if (pkgs == null) {
9870                    pkgs = new ArraySet<>();
9871                    mAppOpPermissionPackages.put(bp.name, pkgs);
9872                }
9873                pkgs.add(pkg.packageName);
9874            }
9875
9876            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9877            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9878                    >= Build.VERSION_CODES.M;
9879            switch (level) {
9880                case PermissionInfo.PROTECTION_NORMAL: {
9881                    // For all apps normal permissions are install time ones.
9882                    grant = GRANT_INSTALL;
9883                } break;
9884
9885                case PermissionInfo.PROTECTION_DANGEROUS: {
9886                    // If a permission review is required for legacy apps we represent
9887                    // their permissions as always granted runtime ones since we need
9888                    // to keep the review required permission flag per user while an
9889                    // install permission's state is shared across all users.
9890                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9891                        // For legacy apps dangerous permissions are install time ones.
9892                        grant = GRANT_INSTALL;
9893                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9894                        // For legacy apps that became modern, install becomes runtime.
9895                        grant = GRANT_UPGRADE;
9896                    } else if (mPromoteSystemApps
9897                            && isSystemApp(ps)
9898                            && mExistingSystemPackages.contains(ps.name)) {
9899                        // For legacy system apps, install becomes runtime.
9900                        // We cannot check hasInstallPermission() for system apps since those
9901                        // permissions were granted implicitly and not persisted pre-M.
9902                        grant = GRANT_UPGRADE;
9903                    } else {
9904                        // For modern apps keep runtime permissions unchanged.
9905                        grant = GRANT_RUNTIME;
9906                    }
9907                } break;
9908
9909                case PermissionInfo.PROTECTION_SIGNATURE: {
9910                    // For all apps signature permissions are install time ones.
9911                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9912                    if (allowedSig) {
9913                        grant = GRANT_INSTALL;
9914                    }
9915                } break;
9916            }
9917
9918            if (DEBUG_INSTALL) {
9919                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9920            }
9921
9922            if (grant != GRANT_DENIED) {
9923                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9924                    // If this is an existing, non-system package, then
9925                    // we can't add any new permissions to it.
9926                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9927                        // Except...  if this is a permission that was added
9928                        // to the platform (note: need to only do this when
9929                        // updating the platform).
9930                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9931                            grant = GRANT_DENIED;
9932                        }
9933                    }
9934                }
9935
9936                switch (grant) {
9937                    case GRANT_INSTALL: {
9938                        // Revoke this as runtime permission to handle the case of
9939                        // a runtime permission being downgraded to an install one.
9940                        // Also in permission review mode we keep dangerous permissions
9941                        // for legacy apps
9942                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9943                            if (origPermissions.getRuntimePermissionState(
9944                                    bp.name, userId) != null) {
9945                                // Revoke the runtime permission and clear the flags.
9946                                origPermissions.revokeRuntimePermission(bp, userId);
9947                                origPermissions.updatePermissionFlags(bp, userId,
9948                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9949                                // If we revoked a permission permission, we have to write.
9950                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9951                                        changedRuntimePermissionUserIds, userId);
9952                            }
9953                        }
9954                        // Grant an install permission.
9955                        if (permissionsState.grantInstallPermission(bp) !=
9956                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9957                            changedInstallPermission = true;
9958                        }
9959                    } break;
9960
9961                    case GRANT_RUNTIME: {
9962                        // Grant previously granted runtime permissions.
9963                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9964                            PermissionState permissionState = origPermissions
9965                                    .getRuntimePermissionState(bp.name, userId);
9966                            int flags = permissionState != null
9967                                    ? permissionState.getFlags() : 0;
9968                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9969                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9970                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9971                                    // If we cannot put the permission as it was, we have to write.
9972                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9973                                            changedRuntimePermissionUserIds, userId);
9974                                }
9975                                // If the app supports runtime permissions no need for a review.
9976                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9977                                        && appSupportsRuntimePermissions
9978                                        && (flags & PackageManager
9979                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9980                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9981                                    // Since we changed the flags, we have to write.
9982                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9983                                            changedRuntimePermissionUserIds, userId);
9984                                }
9985                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9986                                    && !appSupportsRuntimePermissions) {
9987                                // For legacy apps that need a permission review, every new
9988                                // runtime permission is granted but it is pending a review.
9989                                // We also need to review only platform defined runtime
9990                                // permissions as these are the only ones the platform knows
9991                                // how to disable the API to simulate revocation as legacy
9992                                // apps don't expect to run with revoked permissions.
9993                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
9994                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9995                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9996                                        // We changed the flags, hence have to write.
9997                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9998                                                changedRuntimePermissionUserIds, userId);
9999                                    }
10000                                }
10001                                if (permissionsState.grantRuntimePermission(bp, userId)
10002                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10003                                    // We changed the permission, hence have to write.
10004                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10005                                            changedRuntimePermissionUserIds, userId);
10006                                }
10007                            }
10008                            // Propagate the permission flags.
10009                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10010                        }
10011                    } break;
10012
10013                    case GRANT_UPGRADE: {
10014                        // Grant runtime permissions for a previously held install permission.
10015                        PermissionState permissionState = origPermissions
10016                                .getInstallPermissionState(bp.name);
10017                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10018
10019                        if (origPermissions.revokeInstallPermission(bp)
10020                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10021                            // We will be transferring the permission flags, so clear them.
10022                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10023                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10024                            changedInstallPermission = true;
10025                        }
10026
10027                        // If the permission is not to be promoted to runtime we ignore it and
10028                        // also its other flags as they are not applicable to install permissions.
10029                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10030                            for (int userId : currentUserIds) {
10031                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10032                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10033                                    // Transfer the permission flags.
10034                                    permissionsState.updatePermissionFlags(bp, userId,
10035                                            flags, flags);
10036                                    // If we granted the permission, we have to write.
10037                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10038                                            changedRuntimePermissionUserIds, userId);
10039                                }
10040                            }
10041                        }
10042                    } break;
10043
10044                    default: {
10045                        if (packageOfInterest == null
10046                                || packageOfInterest.equals(pkg.packageName)) {
10047                            Slog.w(TAG, "Not granting permission " + perm
10048                                    + " to package " + pkg.packageName
10049                                    + " because it was previously installed without");
10050                        }
10051                    } break;
10052                }
10053            } else {
10054                if (permissionsState.revokeInstallPermission(bp) !=
10055                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10056                    // Also drop the permission flags.
10057                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10058                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10059                    changedInstallPermission = true;
10060                    Slog.i(TAG, "Un-granting permission " + perm
10061                            + " from package " + pkg.packageName
10062                            + " (protectionLevel=" + bp.protectionLevel
10063                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10064                            + ")");
10065                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10066                    // Don't print warning for app op permissions, since it is fine for them
10067                    // not to be granted, there is a UI for the user to decide.
10068                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10069                        Slog.w(TAG, "Not granting permission " + perm
10070                                + " to package " + pkg.packageName
10071                                + " (protectionLevel=" + bp.protectionLevel
10072                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10073                                + ")");
10074                    }
10075                }
10076            }
10077        }
10078
10079        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10080                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10081            // This is the first that we have heard about this package, so the
10082            // permissions we have now selected are fixed until explicitly
10083            // changed.
10084            ps.installPermissionsFixed = true;
10085        }
10086
10087        // Persist the runtime permissions state for users with changes. If permissions
10088        // were revoked because no app in the shared user declares them we have to
10089        // write synchronously to avoid losing runtime permissions state.
10090        for (int userId : changedRuntimePermissionUserIds) {
10091            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10092        }
10093
10094        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10095    }
10096
10097    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10098        boolean allowed = false;
10099        final int NP = PackageParser.NEW_PERMISSIONS.length;
10100        for (int ip=0; ip<NP; ip++) {
10101            final PackageParser.NewPermissionInfo npi
10102                    = PackageParser.NEW_PERMISSIONS[ip];
10103            if (npi.name.equals(perm)
10104                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10105                allowed = true;
10106                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10107                        + pkg.packageName);
10108                break;
10109            }
10110        }
10111        return allowed;
10112    }
10113
10114    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10115            BasePermission bp, PermissionsState origPermissions) {
10116        boolean allowed;
10117        allowed = (compareSignatures(
10118                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10119                        == PackageManager.SIGNATURE_MATCH)
10120                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10121                        == PackageManager.SIGNATURE_MATCH);
10122        if (!allowed && (bp.protectionLevel
10123                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10124            if (isSystemApp(pkg)) {
10125                // For updated system applications, a system permission
10126                // is granted only if it had been defined by the original application.
10127                if (pkg.isUpdatedSystemApp()) {
10128                    final PackageSetting sysPs = mSettings
10129                            .getDisabledSystemPkgLPr(pkg.packageName);
10130                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10131                        // If the original was granted this permission, we take
10132                        // that grant decision as read and propagate it to the
10133                        // update.
10134                        if (sysPs.isPrivileged()) {
10135                            allowed = true;
10136                        }
10137                    } else {
10138                        // The system apk may have been updated with an older
10139                        // version of the one on the data partition, but which
10140                        // granted a new system permission that it didn't have
10141                        // before.  In this case we do want to allow the app to
10142                        // now get the new permission if the ancestral apk is
10143                        // privileged to get it.
10144                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10145                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10146                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10147                                    allowed = true;
10148                                    break;
10149                                }
10150                            }
10151                        }
10152                        // Also if a privileged parent package on the system image or any of
10153                        // its children requested a privileged permission, the updated child
10154                        // packages can also get the permission.
10155                        if (pkg.parentPackage != null) {
10156                            final PackageSetting disabledSysParentPs = mSettings
10157                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10158                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10159                                    && disabledSysParentPs.isPrivileged()) {
10160                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10161                                    allowed = true;
10162                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10163                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10164                                    for (int i = 0; i < count; i++) {
10165                                        PackageParser.Package disabledSysChildPkg =
10166                                                disabledSysParentPs.pkg.childPackages.get(i);
10167                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10168                                                perm)) {
10169                                            allowed = true;
10170                                            break;
10171                                        }
10172                                    }
10173                                }
10174                            }
10175                        }
10176                    }
10177                } else {
10178                    allowed = isPrivilegedApp(pkg);
10179                }
10180            }
10181        }
10182        if (!allowed) {
10183            if (!allowed && (bp.protectionLevel
10184                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10185                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10186                // If this was a previously normal/dangerous permission that got moved
10187                // to a system permission as part of the runtime permission redesign, then
10188                // we still want to blindly grant it to old apps.
10189                allowed = true;
10190            }
10191            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10192                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10193                // If this permission is to be granted to the system installer and
10194                // this app is an installer, then it gets the permission.
10195                allowed = true;
10196            }
10197            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10198                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10199                // If this permission is to be granted to the system verifier and
10200                // this app is a verifier, then it gets the permission.
10201                allowed = true;
10202            }
10203            if (!allowed && (bp.protectionLevel
10204                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10205                    && isSystemApp(pkg)) {
10206                // Any pre-installed system app is allowed to get this permission.
10207                allowed = true;
10208            }
10209            if (!allowed && (bp.protectionLevel
10210                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10211                // For development permissions, a development permission
10212                // is granted only if it was already granted.
10213                allowed = origPermissions.hasInstallPermission(perm);
10214            }
10215            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10216                    && pkg.packageName.equals(mSetupWizardPackage)) {
10217                // If this permission is to be granted to the system setup wizard and
10218                // this app is a setup wizard, then it gets the permission.
10219                allowed = true;
10220            }
10221        }
10222        return allowed;
10223    }
10224
10225    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10226        final int permCount = pkg.requestedPermissions.size();
10227        for (int j = 0; j < permCount; j++) {
10228            String requestedPermission = pkg.requestedPermissions.get(j);
10229            if (permission.equals(requestedPermission)) {
10230                return true;
10231            }
10232        }
10233        return false;
10234    }
10235
10236    final class ActivityIntentResolver
10237            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10238        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10239                boolean defaultOnly, int userId) {
10240            if (!sUserManager.exists(userId)) return null;
10241            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10242            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10243        }
10244
10245        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10246                int userId) {
10247            if (!sUserManager.exists(userId)) return null;
10248            mFlags = flags;
10249            return super.queryIntent(intent, resolvedType,
10250                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10251        }
10252
10253        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10254                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10255            if (!sUserManager.exists(userId)) return null;
10256            if (packageActivities == null) {
10257                return null;
10258            }
10259            mFlags = flags;
10260            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10261            final int N = packageActivities.size();
10262            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10263                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10264
10265            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10266            for (int i = 0; i < N; ++i) {
10267                intentFilters = packageActivities.get(i).intents;
10268                if (intentFilters != null && intentFilters.size() > 0) {
10269                    PackageParser.ActivityIntentInfo[] array =
10270                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10271                    intentFilters.toArray(array);
10272                    listCut.add(array);
10273                }
10274            }
10275            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10276        }
10277
10278        /**
10279         * Finds a privileged activity that matches the specified activity names.
10280         */
10281        private PackageParser.Activity findMatchingActivity(
10282                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10283            for (PackageParser.Activity sysActivity : activityList) {
10284                if (sysActivity.info.name.equals(activityInfo.name)) {
10285                    return sysActivity;
10286                }
10287                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10288                    return sysActivity;
10289                }
10290                if (sysActivity.info.targetActivity != null) {
10291                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10292                        return sysActivity;
10293                    }
10294                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10295                        return sysActivity;
10296                    }
10297                }
10298            }
10299            return null;
10300        }
10301
10302        public class IterGenerator<E> {
10303            public Iterator<E> generate(ActivityIntentInfo info) {
10304                return null;
10305            }
10306        }
10307
10308        public class ActionIterGenerator extends IterGenerator<String> {
10309            @Override
10310            public Iterator<String> generate(ActivityIntentInfo info) {
10311                return info.actionsIterator();
10312            }
10313        }
10314
10315        public class CategoriesIterGenerator extends IterGenerator<String> {
10316            @Override
10317            public Iterator<String> generate(ActivityIntentInfo info) {
10318                return info.categoriesIterator();
10319            }
10320        }
10321
10322        public class SchemesIterGenerator extends IterGenerator<String> {
10323            @Override
10324            public Iterator<String> generate(ActivityIntentInfo info) {
10325                return info.schemesIterator();
10326            }
10327        }
10328
10329        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10330            @Override
10331            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10332                return info.authoritiesIterator();
10333            }
10334        }
10335
10336        /**
10337         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10338         * MODIFIED. Do not pass in a list that should not be changed.
10339         */
10340        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10341                IterGenerator<T> generator, Iterator<T> searchIterator) {
10342            // loop through the set of actions; every one must be found in the intent filter
10343            while (searchIterator.hasNext()) {
10344                // we must have at least one filter in the list to consider a match
10345                if (intentList.size() == 0) {
10346                    break;
10347                }
10348
10349                final T searchAction = searchIterator.next();
10350
10351                // loop through the set of intent filters
10352                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10353                while (intentIter.hasNext()) {
10354                    final ActivityIntentInfo intentInfo = intentIter.next();
10355                    boolean selectionFound = false;
10356
10357                    // loop through the intent filter's selection criteria; at least one
10358                    // of them must match the searched criteria
10359                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10360                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10361                        final T intentSelection = intentSelectionIter.next();
10362                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10363                            selectionFound = true;
10364                            break;
10365                        }
10366                    }
10367
10368                    // the selection criteria wasn't found in this filter's set; this filter
10369                    // is not a potential match
10370                    if (!selectionFound) {
10371                        intentIter.remove();
10372                    }
10373                }
10374            }
10375        }
10376
10377        private boolean isProtectedAction(ActivityIntentInfo filter) {
10378            final Iterator<String> actionsIter = filter.actionsIterator();
10379            while (actionsIter != null && actionsIter.hasNext()) {
10380                final String filterAction = actionsIter.next();
10381                if (PROTECTED_ACTIONS.contains(filterAction)) {
10382                    return true;
10383                }
10384            }
10385            return false;
10386        }
10387
10388        /**
10389         * Adjusts the priority of the given intent filter according to policy.
10390         * <p>
10391         * <ul>
10392         * <li>The priority for non privileged applications is capped to '0'</li>
10393         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10394         * <li>The priority for unbundled updates to privileged applications is capped to the
10395         *      priority defined on the system partition</li>
10396         * </ul>
10397         * <p>
10398         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10399         * allowed to obtain any priority on any action.
10400         */
10401        private void adjustPriority(
10402                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10403            // nothing to do; priority is fine as-is
10404            if (intent.getPriority() <= 0) {
10405                return;
10406            }
10407
10408            final ActivityInfo activityInfo = intent.activity.info;
10409            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10410
10411            final boolean privilegedApp =
10412                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10413            if (!privilegedApp) {
10414                // non-privileged applications can never define a priority >0
10415                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10416                        + " package: " + applicationInfo.packageName
10417                        + " activity: " + intent.activity.className
10418                        + " origPrio: " + intent.getPriority());
10419                intent.setPriority(0);
10420                return;
10421            }
10422
10423            if (systemActivities == null) {
10424                // the system package is not disabled; we're parsing the system partition
10425                if (isProtectedAction(intent)) {
10426                    if (mDeferProtectedFilters) {
10427                        // We can't deal with these just yet. No component should ever obtain a
10428                        // >0 priority for a protected actions, with ONE exception -- the setup
10429                        // wizard. The setup wizard, however, cannot be known until we're able to
10430                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10431                        // until all intent filters have been processed. Chicken, meet egg.
10432                        // Let the filter temporarily have a high priority and rectify the
10433                        // priorities after all system packages have been scanned.
10434                        mProtectedFilters.add(intent);
10435                        if (DEBUG_FILTERS) {
10436                            Slog.i(TAG, "Protected action; save for later;"
10437                                    + " package: " + applicationInfo.packageName
10438                                    + " activity: " + intent.activity.className
10439                                    + " origPrio: " + intent.getPriority());
10440                        }
10441                        return;
10442                    } else {
10443                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10444                            Slog.i(TAG, "No setup wizard;"
10445                                + " All protected intents capped to priority 0");
10446                        }
10447                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10448                            if (DEBUG_FILTERS) {
10449                                Slog.i(TAG, "Found setup wizard;"
10450                                    + " allow priority " + intent.getPriority() + ";"
10451                                    + " package: " + intent.activity.info.packageName
10452                                    + " activity: " + intent.activity.className
10453                                    + " priority: " + intent.getPriority());
10454                            }
10455                            // setup wizard gets whatever it wants
10456                            return;
10457                        }
10458                        Slog.w(TAG, "Protected action; cap priority to 0;"
10459                                + " package: " + intent.activity.info.packageName
10460                                + " activity: " + intent.activity.className
10461                                + " origPrio: " + intent.getPriority());
10462                        intent.setPriority(0);
10463                        return;
10464                    }
10465                }
10466                // privileged apps on the system image get whatever priority they request
10467                return;
10468            }
10469
10470            // privileged app unbundled update ... try to find the same activity
10471            final PackageParser.Activity foundActivity =
10472                    findMatchingActivity(systemActivities, activityInfo);
10473            if (foundActivity == null) {
10474                // this is a new activity; it cannot obtain >0 priority
10475                if (DEBUG_FILTERS) {
10476                    Slog.i(TAG, "New activity; cap priority to 0;"
10477                            + " package: " + applicationInfo.packageName
10478                            + " activity: " + intent.activity.className
10479                            + " origPrio: " + intent.getPriority());
10480                }
10481                intent.setPriority(0);
10482                return;
10483            }
10484
10485            // found activity, now check for filter equivalence
10486
10487            // a shallow copy is enough; we modify the list, not its contents
10488            final List<ActivityIntentInfo> intentListCopy =
10489                    new ArrayList<>(foundActivity.intents);
10490            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10491
10492            // find matching action subsets
10493            final Iterator<String> actionsIterator = intent.actionsIterator();
10494            if (actionsIterator != null) {
10495                getIntentListSubset(
10496                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10497                if (intentListCopy.size() == 0) {
10498                    // no more intents to match; we're not equivalent
10499                    if (DEBUG_FILTERS) {
10500                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10501                                + " package: " + applicationInfo.packageName
10502                                + " activity: " + intent.activity.className
10503                                + " origPrio: " + intent.getPriority());
10504                    }
10505                    intent.setPriority(0);
10506                    return;
10507                }
10508            }
10509
10510            // find matching category subsets
10511            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10512            if (categoriesIterator != null) {
10513                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10514                        categoriesIterator);
10515                if (intentListCopy.size() == 0) {
10516                    // no more intents to match; we're not equivalent
10517                    if (DEBUG_FILTERS) {
10518                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10519                                + " package: " + applicationInfo.packageName
10520                                + " activity: " + intent.activity.className
10521                                + " origPrio: " + intent.getPriority());
10522                    }
10523                    intent.setPriority(0);
10524                    return;
10525                }
10526            }
10527
10528            // find matching schemes subsets
10529            final Iterator<String> schemesIterator = intent.schemesIterator();
10530            if (schemesIterator != null) {
10531                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10532                        schemesIterator);
10533                if (intentListCopy.size() == 0) {
10534                    // no more intents to match; we're not equivalent
10535                    if (DEBUG_FILTERS) {
10536                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10537                                + " package: " + applicationInfo.packageName
10538                                + " activity: " + intent.activity.className
10539                                + " origPrio: " + intent.getPriority());
10540                    }
10541                    intent.setPriority(0);
10542                    return;
10543                }
10544            }
10545
10546            // find matching authorities subsets
10547            final Iterator<IntentFilter.AuthorityEntry>
10548                    authoritiesIterator = intent.authoritiesIterator();
10549            if (authoritiesIterator != null) {
10550                getIntentListSubset(intentListCopy,
10551                        new AuthoritiesIterGenerator(),
10552                        authoritiesIterator);
10553                if (intentListCopy.size() == 0) {
10554                    // no more intents to match; we're not equivalent
10555                    if (DEBUG_FILTERS) {
10556                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10557                                + " package: " + applicationInfo.packageName
10558                                + " activity: " + intent.activity.className
10559                                + " origPrio: " + intent.getPriority());
10560                    }
10561                    intent.setPriority(0);
10562                    return;
10563                }
10564            }
10565
10566            // we found matching filter(s); app gets the max priority of all intents
10567            int cappedPriority = 0;
10568            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10569                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10570            }
10571            if (intent.getPriority() > cappedPriority) {
10572                if (DEBUG_FILTERS) {
10573                    Slog.i(TAG, "Found matching filter(s);"
10574                            + " cap priority to " + cappedPriority + ";"
10575                            + " package: " + applicationInfo.packageName
10576                            + " activity: " + intent.activity.className
10577                            + " origPrio: " + intent.getPriority());
10578                }
10579                intent.setPriority(cappedPriority);
10580                return;
10581            }
10582            // all this for nothing; the requested priority was <= what was on the system
10583        }
10584
10585        public final void addActivity(PackageParser.Activity a, String type) {
10586            mActivities.put(a.getComponentName(), a);
10587            if (DEBUG_SHOW_INFO)
10588                Log.v(
10589                TAG, "  " + type + " " +
10590                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10591            if (DEBUG_SHOW_INFO)
10592                Log.v(TAG, "    Class=" + a.info.name);
10593            final int NI = a.intents.size();
10594            for (int j=0; j<NI; j++) {
10595                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10596                if ("activity".equals(type)) {
10597                    final PackageSetting ps =
10598                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10599                    final List<PackageParser.Activity> systemActivities =
10600                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10601                    adjustPriority(systemActivities, intent);
10602                }
10603                if (DEBUG_SHOW_INFO) {
10604                    Log.v(TAG, "    IntentFilter:");
10605                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10606                }
10607                if (!intent.debugCheck()) {
10608                    Log.w(TAG, "==> For Activity " + a.info.name);
10609                }
10610                addFilter(intent);
10611            }
10612        }
10613
10614        public final void removeActivity(PackageParser.Activity a, String type) {
10615            mActivities.remove(a.getComponentName());
10616            if (DEBUG_SHOW_INFO) {
10617                Log.v(TAG, "  " + type + " "
10618                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10619                                : a.info.name) + ":");
10620                Log.v(TAG, "    Class=" + a.info.name);
10621            }
10622            final int NI = a.intents.size();
10623            for (int j=0; j<NI; j++) {
10624                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10625                if (DEBUG_SHOW_INFO) {
10626                    Log.v(TAG, "    IntentFilter:");
10627                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10628                }
10629                removeFilter(intent);
10630            }
10631        }
10632
10633        @Override
10634        protected boolean allowFilterResult(
10635                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10636            ActivityInfo filterAi = filter.activity.info;
10637            for (int i=dest.size()-1; i>=0; i--) {
10638                ActivityInfo destAi = dest.get(i).activityInfo;
10639                if (destAi.name == filterAi.name
10640                        && destAi.packageName == filterAi.packageName) {
10641                    return false;
10642                }
10643            }
10644            return true;
10645        }
10646
10647        @Override
10648        protected ActivityIntentInfo[] newArray(int size) {
10649            return new ActivityIntentInfo[size];
10650        }
10651
10652        @Override
10653        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10654            if (!sUserManager.exists(userId)) return true;
10655            PackageParser.Package p = filter.activity.owner;
10656            if (p != null) {
10657                PackageSetting ps = (PackageSetting)p.mExtras;
10658                if (ps != null) {
10659                    // System apps are never considered stopped for purposes of
10660                    // filtering, because there may be no way for the user to
10661                    // actually re-launch them.
10662                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10663                            && ps.getStopped(userId);
10664                }
10665            }
10666            return false;
10667        }
10668
10669        @Override
10670        protected boolean isPackageForFilter(String packageName,
10671                PackageParser.ActivityIntentInfo info) {
10672            return packageName.equals(info.activity.owner.packageName);
10673        }
10674
10675        @Override
10676        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10677                int match, int userId) {
10678            if (!sUserManager.exists(userId)) return null;
10679            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10680                return null;
10681            }
10682            final PackageParser.Activity activity = info.activity;
10683            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10684            if (ps == null) {
10685                return null;
10686            }
10687            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10688                    ps.readUserState(userId), userId);
10689            if (ai == null) {
10690                return null;
10691            }
10692            final ResolveInfo res = new ResolveInfo();
10693            res.activityInfo = ai;
10694            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10695                res.filter = info;
10696            }
10697            if (info != null) {
10698                res.handleAllWebDataURI = info.handleAllWebDataURI();
10699            }
10700            res.priority = info.getPriority();
10701            res.preferredOrder = activity.owner.mPreferredOrder;
10702            //System.out.println("Result: " + res.activityInfo.className +
10703            //                   " = " + res.priority);
10704            res.match = match;
10705            res.isDefault = info.hasDefault;
10706            res.labelRes = info.labelRes;
10707            res.nonLocalizedLabel = info.nonLocalizedLabel;
10708            if (userNeedsBadging(userId)) {
10709                res.noResourceId = true;
10710            } else {
10711                res.icon = info.icon;
10712            }
10713            res.iconResourceId = info.icon;
10714            res.system = res.activityInfo.applicationInfo.isSystemApp();
10715            return res;
10716        }
10717
10718        @Override
10719        protected void sortResults(List<ResolveInfo> results) {
10720            Collections.sort(results, mResolvePrioritySorter);
10721        }
10722
10723        @Override
10724        protected void dumpFilter(PrintWriter out, String prefix,
10725                PackageParser.ActivityIntentInfo filter) {
10726            out.print(prefix); out.print(
10727                    Integer.toHexString(System.identityHashCode(filter.activity)));
10728                    out.print(' ');
10729                    filter.activity.printComponentShortName(out);
10730                    out.print(" filter ");
10731                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10732        }
10733
10734        @Override
10735        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10736            return filter.activity;
10737        }
10738
10739        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10740            PackageParser.Activity activity = (PackageParser.Activity)label;
10741            out.print(prefix); out.print(
10742                    Integer.toHexString(System.identityHashCode(activity)));
10743                    out.print(' ');
10744                    activity.printComponentShortName(out);
10745            if (count > 1) {
10746                out.print(" ("); out.print(count); out.print(" filters)");
10747            }
10748            out.println();
10749        }
10750
10751        // Keys are String (activity class name), values are Activity.
10752        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10753                = new ArrayMap<ComponentName, PackageParser.Activity>();
10754        private int mFlags;
10755    }
10756
10757    private final class ServiceIntentResolver
10758            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10759        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10760                boolean defaultOnly, int userId) {
10761            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10762            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10763        }
10764
10765        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10766                int userId) {
10767            if (!sUserManager.exists(userId)) return null;
10768            mFlags = flags;
10769            return super.queryIntent(intent, resolvedType,
10770                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10771        }
10772
10773        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10774                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10775            if (!sUserManager.exists(userId)) return null;
10776            if (packageServices == null) {
10777                return null;
10778            }
10779            mFlags = flags;
10780            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10781            final int N = packageServices.size();
10782            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10783                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10784
10785            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10786            for (int i = 0; i < N; ++i) {
10787                intentFilters = packageServices.get(i).intents;
10788                if (intentFilters != null && intentFilters.size() > 0) {
10789                    PackageParser.ServiceIntentInfo[] array =
10790                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10791                    intentFilters.toArray(array);
10792                    listCut.add(array);
10793                }
10794            }
10795            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10796        }
10797
10798        public final void addService(PackageParser.Service s) {
10799            mServices.put(s.getComponentName(), s);
10800            if (DEBUG_SHOW_INFO) {
10801                Log.v(TAG, "  "
10802                        + (s.info.nonLocalizedLabel != null
10803                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10804                Log.v(TAG, "    Class=" + s.info.name);
10805            }
10806            final int NI = s.intents.size();
10807            int j;
10808            for (j=0; j<NI; j++) {
10809                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10810                if (DEBUG_SHOW_INFO) {
10811                    Log.v(TAG, "    IntentFilter:");
10812                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10813                }
10814                if (!intent.debugCheck()) {
10815                    Log.w(TAG, "==> For Service " + s.info.name);
10816                }
10817                addFilter(intent);
10818            }
10819        }
10820
10821        public final void removeService(PackageParser.Service s) {
10822            mServices.remove(s.getComponentName());
10823            if (DEBUG_SHOW_INFO) {
10824                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10825                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10826                Log.v(TAG, "    Class=" + s.info.name);
10827            }
10828            final int NI = s.intents.size();
10829            int j;
10830            for (j=0; j<NI; j++) {
10831                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10832                if (DEBUG_SHOW_INFO) {
10833                    Log.v(TAG, "    IntentFilter:");
10834                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10835                }
10836                removeFilter(intent);
10837            }
10838        }
10839
10840        @Override
10841        protected boolean allowFilterResult(
10842                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10843            ServiceInfo filterSi = filter.service.info;
10844            for (int i=dest.size()-1; i>=0; i--) {
10845                ServiceInfo destAi = dest.get(i).serviceInfo;
10846                if (destAi.name == filterSi.name
10847                        && destAi.packageName == filterSi.packageName) {
10848                    return false;
10849                }
10850            }
10851            return true;
10852        }
10853
10854        @Override
10855        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10856            return new PackageParser.ServiceIntentInfo[size];
10857        }
10858
10859        @Override
10860        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10861            if (!sUserManager.exists(userId)) return true;
10862            PackageParser.Package p = filter.service.owner;
10863            if (p != null) {
10864                PackageSetting ps = (PackageSetting)p.mExtras;
10865                if (ps != null) {
10866                    // System apps are never considered stopped for purposes of
10867                    // filtering, because there may be no way for the user to
10868                    // actually re-launch them.
10869                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10870                            && ps.getStopped(userId);
10871                }
10872            }
10873            return false;
10874        }
10875
10876        @Override
10877        protected boolean isPackageForFilter(String packageName,
10878                PackageParser.ServiceIntentInfo info) {
10879            return packageName.equals(info.service.owner.packageName);
10880        }
10881
10882        @Override
10883        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10884                int match, int userId) {
10885            if (!sUserManager.exists(userId)) return null;
10886            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10887            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10888                return null;
10889            }
10890            final PackageParser.Service service = info.service;
10891            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10892            if (ps == null) {
10893                return null;
10894            }
10895            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10896                    ps.readUserState(userId), userId);
10897            if (si == null) {
10898                return null;
10899            }
10900            final ResolveInfo res = new ResolveInfo();
10901            res.serviceInfo = si;
10902            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10903                res.filter = filter;
10904            }
10905            res.priority = info.getPriority();
10906            res.preferredOrder = service.owner.mPreferredOrder;
10907            res.match = match;
10908            res.isDefault = info.hasDefault;
10909            res.labelRes = info.labelRes;
10910            res.nonLocalizedLabel = info.nonLocalizedLabel;
10911            res.icon = info.icon;
10912            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10913            return res;
10914        }
10915
10916        @Override
10917        protected void sortResults(List<ResolveInfo> results) {
10918            Collections.sort(results, mResolvePrioritySorter);
10919        }
10920
10921        @Override
10922        protected void dumpFilter(PrintWriter out, String prefix,
10923                PackageParser.ServiceIntentInfo filter) {
10924            out.print(prefix); out.print(
10925                    Integer.toHexString(System.identityHashCode(filter.service)));
10926                    out.print(' ');
10927                    filter.service.printComponentShortName(out);
10928                    out.print(" filter ");
10929                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10930        }
10931
10932        @Override
10933        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10934            return filter.service;
10935        }
10936
10937        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10938            PackageParser.Service service = (PackageParser.Service)label;
10939            out.print(prefix); out.print(
10940                    Integer.toHexString(System.identityHashCode(service)));
10941                    out.print(' ');
10942                    service.printComponentShortName(out);
10943            if (count > 1) {
10944                out.print(" ("); out.print(count); out.print(" filters)");
10945            }
10946            out.println();
10947        }
10948
10949//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10950//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10951//            final List<ResolveInfo> retList = Lists.newArrayList();
10952//            while (i.hasNext()) {
10953//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10954//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10955//                    retList.add(resolveInfo);
10956//                }
10957//            }
10958//            return retList;
10959//        }
10960
10961        // Keys are String (activity class name), values are Activity.
10962        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10963                = new ArrayMap<ComponentName, PackageParser.Service>();
10964        private int mFlags;
10965    };
10966
10967    private final class ProviderIntentResolver
10968            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10969        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10970                boolean defaultOnly, int userId) {
10971            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10972            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10973        }
10974
10975        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10976                int userId) {
10977            if (!sUserManager.exists(userId))
10978                return null;
10979            mFlags = flags;
10980            return super.queryIntent(intent, resolvedType,
10981                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10982        }
10983
10984        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10985                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10986            if (!sUserManager.exists(userId))
10987                return null;
10988            if (packageProviders == null) {
10989                return null;
10990            }
10991            mFlags = flags;
10992            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10993            final int N = packageProviders.size();
10994            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10995                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10996
10997            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10998            for (int i = 0; i < N; ++i) {
10999                intentFilters = packageProviders.get(i).intents;
11000                if (intentFilters != null && intentFilters.size() > 0) {
11001                    PackageParser.ProviderIntentInfo[] array =
11002                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11003                    intentFilters.toArray(array);
11004                    listCut.add(array);
11005                }
11006            }
11007            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11008        }
11009
11010        public final void addProvider(PackageParser.Provider p) {
11011            if (mProviders.containsKey(p.getComponentName())) {
11012                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11013                return;
11014            }
11015
11016            mProviders.put(p.getComponentName(), p);
11017            if (DEBUG_SHOW_INFO) {
11018                Log.v(TAG, "  "
11019                        + (p.info.nonLocalizedLabel != null
11020                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11021                Log.v(TAG, "    Class=" + p.info.name);
11022            }
11023            final int NI = p.intents.size();
11024            int j;
11025            for (j = 0; j < NI; j++) {
11026                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11027                if (DEBUG_SHOW_INFO) {
11028                    Log.v(TAG, "    IntentFilter:");
11029                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11030                }
11031                if (!intent.debugCheck()) {
11032                    Log.w(TAG, "==> For Provider " + p.info.name);
11033                }
11034                addFilter(intent);
11035            }
11036        }
11037
11038        public final void removeProvider(PackageParser.Provider p) {
11039            mProviders.remove(p.getComponentName());
11040            if (DEBUG_SHOW_INFO) {
11041                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11042                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11043                Log.v(TAG, "    Class=" + p.info.name);
11044            }
11045            final int NI = p.intents.size();
11046            int j;
11047            for (j = 0; j < NI; j++) {
11048                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11049                if (DEBUG_SHOW_INFO) {
11050                    Log.v(TAG, "    IntentFilter:");
11051                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11052                }
11053                removeFilter(intent);
11054            }
11055        }
11056
11057        @Override
11058        protected boolean allowFilterResult(
11059                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11060            ProviderInfo filterPi = filter.provider.info;
11061            for (int i = dest.size() - 1; i >= 0; i--) {
11062                ProviderInfo destPi = dest.get(i).providerInfo;
11063                if (destPi.name == filterPi.name
11064                        && destPi.packageName == filterPi.packageName) {
11065                    return false;
11066                }
11067            }
11068            return true;
11069        }
11070
11071        @Override
11072        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11073            return new PackageParser.ProviderIntentInfo[size];
11074        }
11075
11076        @Override
11077        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11078            if (!sUserManager.exists(userId))
11079                return true;
11080            PackageParser.Package p = filter.provider.owner;
11081            if (p != null) {
11082                PackageSetting ps = (PackageSetting) p.mExtras;
11083                if (ps != null) {
11084                    // System apps are never considered stopped for purposes of
11085                    // filtering, because there may be no way for the user to
11086                    // actually re-launch them.
11087                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11088                            && ps.getStopped(userId);
11089                }
11090            }
11091            return false;
11092        }
11093
11094        @Override
11095        protected boolean isPackageForFilter(String packageName,
11096                PackageParser.ProviderIntentInfo info) {
11097            return packageName.equals(info.provider.owner.packageName);
11098        }
11099
11100        @Override
11101        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11102                int match, int userId) {
11103            if (!sUserManager.exists(userId))
11104                return null;
11105            final PackageParser.ProviderIntentInfo info = filter;
11106            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11107                return null;
11108            }
11109            final PackageParser.Provider provider = info.provider;
11110            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11111            if (ps == null) {
11112                return null;
11113            }
11114            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11115                    ps.readUserState(userId), userId);
11116            if (pi == null) {
11117                return null;
11118            }
11119            final ResolveInfo res = new ResolveInfo();
11120            res.providerInfo = pi;
11121            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11122                res.filter = filter;
11123            }
11124            res.priority = info.getPriority();
11125            res.preferredOrder = provider.owner.mPreferredOrder;
11126            res.match = match;
11127            res.isDefault = info.hasDefault;
11128            res.labelRes = info.labelRes;
11129            res.nonLocalizedLabel = info.nonLocalizedLabel;
11130            res.icon = info.icon;
11131            res.system = res.providerInfo.applicationInfo.isSystemApp();
11132            return res;
11133        }
11134
11135        @Override
11136        protected void sortResults(List<ResolveInfo> results) {
11137            Collections.sort(results, mResolvePrioritySorter);
11138        }
11139
11140        @Override
11141        protected void dumpFilter(PrintWriter out, String prefix,
11142                PackageParser.ProviderIntentInfo filter) {
11143            out.print(prefix);
11144            out.print(
11145                    Integer.toHexString(System.identityHashCode(filter.provider)));
11146            out.print(' ');
11147            filter.provider.printComponentShortName(out);
11148            out.print(" filter ");
11149            out.println(Integer.toHexString(System.identityHashCode(filter)));
11150        }
11151
11152        @Override
11153        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11154            return filter.provider;
11155        }
11156
11157        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11158            PackageParser.Provider provider = (PackageParser.Provider)label;
11159            out.print(prefix); out.print(
11160                    Integer.toHexString(System.identityHashCode(provider)));
11161                    out.print(' ');
11162                    provider.printComponentShortName(out);
11163            if (count > 1) {
11164                out.print(" ("); out.print(count); out.print(" filters)");
11165            }
11166            out.println();
11167        }
11168
11169        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11170                = new ArrayMap<ComponentName, PackageParser.Provider>();
11171        private int mFlags;
11172    }
11173
11174    private static final class EphemeralIntentResolver
11175            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11176        @Override
11177        protected EphemeralResolveIntentInfo[] newArray(int size) {
11178            return new EphemeralResolveIntentInfo[size];
11179        }
11180
11181        @Override
11182        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11183            return true;
11184        }
11185
11186        @Override
11187        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11188                int userId) {
11189            if (!sUserManager.exists(userId)) {
11190                return null;
11191            }
11192            return info.getEphemeralResolveInfo();
11193        }
11194    }
11195
11196    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11197            new Comparator<ResolveInfo>() {
11198        public int compare(ResolveInfo r1, ResolveInfo r2) {
11199            int v1 = r1.priority;
11200            int v2 = r2.priority;
11201            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11202            if (v1 != v2) {
11203                return (v1 > v2) ? -1 : 1;
11204            }
11205            v1 = r1.preferredOrder;
11206            v2 = r2.preferredOrder;
11207            if (v1 != v2) {
11208                return (v1 > v2) ? -1 : 1;
11209            }
11210            if (r1.isDefault != r2.isDefault) {
11211                return r1.isDefault ? -1 : 1;
11212            }
11213            v1 = r1.match;
11214            v2 = r2.match;
11215            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11216            if (v1 != v2) {
11217                return (v1 > v2) ? -1 : 1;
11218            }
11219            if (r1.system != r2.system) {
11220                return r1.system ? -1 : 1;
11221            }
11222            if (r1.activityInfo != null) {
11223                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11224            }
11225            if (r1.serviceInfo != null) {
11226                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11227            }
11228            if (r1.providerInfo != null) {
11229                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11230            }
11231            return 0;
11232        }
11233    };
11234
11235    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11236            new Comparator<ProviderInfo>() {
11237        public int compare(ProviderInfo p1, ProviderInfo p2) {
11238            final int v1 = p1.initOrder;
11239            final int v2 = p2.initOrder;
11240            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11241        }
11242    };
11243
11244    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11245            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11246            final int[] userIds) {
11247        mHandler.post(new Runnable() {
11248            @Override
11249            public void run() {
11250                try {
11251                    final IActivityManager am = ActivityManagerNative.getDefault();
11252                    if (am == null) return;
11253                    final int[] resolvedUserIds;
11254                    if (userIds == null) {
11255                        resolvedUserIds = am.getRunningUserIds();
11256                    } else {
11257                        resolvedUserIds = userIds;
11258                    }
11259                    for (int id : resolvedUserIds) {
11260                        final Intent intent = new Intent(action,
11261                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11262                        if (extras != null) {
11263                            intent.putExtras(extras);
11264                        }
11265                        if (targetPkg != null) {
11266                            intent.setPackage(targetPkg);
11267                        }
11268                        // Modify the UID when posting to other users
11269                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11270                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11271                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11272                            intent.putExtra(Intent.EXTRA_UID, uid);
11273                        }
11274                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11275                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11276                        if (DEBUG_BROADCASTS) {
11277                            RuntimeException here = new RuntimeException("here");
11278                            here.fillInStackTrace();
11279                            Slog.d(TAG, "Sending to user " + id + ": "
11280                                    + intent.toShortString(false, true, false, false)
11281                                    + " " + intent.getExtras(), here);
11282                        }
11283                        am.broadcastIntent(null, intent, null, finishedReceiver,
11284                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11285                                null, finishedReceiver != null, false, id);
11286                    }
11287                } catch (RemoteException ex) {
11288                }
11289            }
11290        });
11291    }
11292
11293    /**
11294     * Check if the external storage media is available. This is true if there
11295     * is a mounted external storage medium or if the external storage is
11296     * emulated.
11297     */
11298    private boolean isExternalMediaAvailable() {
11299        return mMediaMounted || Environment.isExternalStorageEmulated();
11300    }
11301
11302    @Override
11303    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11304        // writer
11305        synchronized (mPackages) {
11306            if (!isExternalMediaAvailable()) {
11307                // If the external storage is no longer mounted at this point,
11308                // the caller may not have been able to delete all of this
11309                // packages files and can not delete any more.  Bail.
11310                return null;
11311            }
11312            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11313            if (lastPackage != null) {
11314                pkgs.remove(lastPackage);
11315            }
11316            if (pkgs.size() > 0) {
11317                return pkgs.get(0);
11318            }
11319        }
11320        return null;
11321    }
11322
11323    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11324        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11325                userId, andCode ? 1 : 0, packageName);
11326        if (mSystemReady) {
11327            msg.sendToTarget();
11328        } else {
11329            if (mPostSystemReadyMessages == null) {
11330                mPostSystemReadyMessages = new ArrayList<>();
11331            }
11332            mPostSystemReadyMessages.add(msg);
11333        }
11334    }
11335
11336    void startCleaningPackages() {
11337        // reader
11338        if (!isExternalMediaAvailable()) {
11339            return;
11340        }
11341        synchronized (mPackages) {
11342            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11343                return;
11344            }
11345        }
11346        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11347        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11348        IActivityManager am = ActivityManagerNative.getDefault();
11349        if (am != null) {
11350            try {
11351                am.startService(null, intent, null, mContext.getOpPackageName(),
11352                        UserHandle.USER_SYSTEM);
11353            } catch (RemoteException e) {
11354            }
11355        }
11356    }
11357
11358    @Override
11359    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11360            int installFlags, String installerPackageName, int userId) {
11361        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11362
11363        final int callingUid = Binder.getCallingUid();
11364        enforceCrossUserPermission(callingUid, userId,
11365                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11366
11367        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11368            try {
11369                if (observer != null) {
11370                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11371                }
11372            } catch (RemoteException re) {
11373            }
11374            return;
11375        }
11376
11377        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11378            installFlags |= PackageManager.INSTALL_FROM_ADB;
11379
11380        } else {
11381            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11382            // about installerPackageName.
11383
11384            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11385            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11386        }
11387
11388        UserHandle user;
11389        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11390            user = UserHandle.ALL;
11391        } else {
11392            user = new UserHandle(userId);
11393        }
11394
11395        // Only system components can circumvent runtime permissions when installing.
11396        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11397                && mContext.checkCallingOrSelfPermission(Manifest.permission
11398                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11399            throw new SecurityException("You need the "
11400                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11401                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11402        }
11403
11404        final File originFile = new File(originPath);
11405        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11406
11407        final Message msg = mHandler.obtainMessage(INIT_COPY);
11408        final VerificationInfo verificationInfo = new VerificationInfo(
11409                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11410        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11411                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11412                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11413                null /*certificates*/);
11414        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11415        msg.obj = params;
11416
11417        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11418                System.identityHashCode(msg.obj));
11419        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11420                System.identityHashCode(msg.obj));
11421
11422        mHandler.sendMessage(msg);
11423    }
11424
11425    void installStage(String packageName, File stagedDir, String stagedCid,
11426            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11427            String installerPackageName, int installerUid, UserHandle user,
11428            Certificate[][] certificates) {
11429        if (DEBUG_EPHEMERAL) {
11430            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11431                Slog.d(TAG, "Ephemeral install of " + packageName);
11432            }
11433        }
11434        final VerificationInfo verificationInfo = new VerificationInfo(
11435                sessionParams.originatingUri, sessionParams.referrerUri,
11436                sessionParams.originatingUid, installerUid);
11437
11438        final OriginInfo origin;
11439        if (stagedDir != null) {
11440            origin = OriginInfo.fromStagedFile(stagedDir);
11441        } else {
11442            origin = OriginInfo.fromStagedContainer(stagedCid);
11443        }
11444
11445        final Message msg = mHandler.obtainMessage(INIT_COPY);
11446        final InstallParams params = new InstallParams(origin, null, observer,
11447                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11448                verificationInfo, user, sessionParams.abiOverride,
11449                sessionParams.grantedRuntimePermissions, certificates);
11450        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11451        msg.obj = params;
11452
11453        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11454                System.identityHashCode(msg.obj));
11455        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11456                System.identityHashCode(msg.obj));
11457
11458        mHandler.sendMessage(msg);
11459    }
11460
11461    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11462            int userId) {
11463        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11464        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11465    }
11466
11467    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11468            int appId, int userId) {
11469        Bundle extras = new Bundle(1);
11470        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11471
11472        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11473                packageName, extras, 0, null, null, new int[] {userId});
11474        try {
11475            IActivityManager am = ActivityManagerNative.getDefault();
11476            if (isSystem && am.isUserRunning(userId, 0)) {
11477                // The just-installed/enabled app is bundled on the system, so presumed
11478                // to be able to run automatically without needing an explicit launch.
11479                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11480                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11481                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11482                        .setPackage(packageName);
11483                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11484                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11485            }
11486        } catch (RemoteException e) {
11487            // shouldn't happen
11488            Slog.w(TAG, "Unable to bootstrap installed package", e);
11489        }
11490    }
11491
11492    @Override
11493    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11494            int userId) {
11495        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11496        PackageSetting pkgSetting;
11497        final int uid = Binder.getCallingUid();
11498        enforceCrossUserPermission(uid, userId,
11499                true /* requireFullPermission */, true /* checkShell */,
11500                "setApplicationHiddenSetting for user " + userId);
11501
11502        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11503            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11504            return false;
11505        }
11506
11507        long callingId = Binder.clearCallingIdentity();
11508        try {
11509            boolean sendAdded = false;
11510            boolean sendRemoved = false;
11511            // writer
11512            synchronized (mPackages) {
11513                pkgSetting = mSettings.mPackages.get(packageName);
11514                if (pkgSetting == null) {
11515                    return false;
11516                }
11517                // Do not allow "android" is being disabled
11518                if ("android".equals(packageName)) {
11519                    Slog.w(TAG, "Cannot hide package: android");
11520                    return false;
11521                }
11522                // Only allow protected packages to hide themselves.
11523                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11524                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11525                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11526                    return false;
11527                }
11528
11529                if (pkgSetting.getHidden(userId) != hidden) {
11530                    pkgSetting.setHidden(hidden, userId);
11531                    mSettings.writePackageRestrictionsLPr(userId);
11532                    if (hidden) {
11533                        sendRemoved = true;
11534                    } else {
11535                        sendAdded = true;
11536                    }
11537                }
11538            }
11539            if (sendAdded) {
11540                sendPackageAddedForUser(packageName, pkgSetting, userId);
11541                return true;
11542            }
11543            if (sendRemoved) {
11544                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11545                        "hiding pkg");
11546                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11547                return true;
11548            }
11549        } finally {
11550            Binder.restoreCallingIdentity(callingId);
11551        }
11552        return false;
11553    }
11554
11555    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11556            int userId) {
11557        final PackageRemovedInfo info = new PackageRemovedInfo();
11558        info.removedPackage = packageName;
11559        info.removedUsers = new int[] {userId};
11560        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11561        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11562    }
11563
11564    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11565        if (pkgList.length > 0) {
11566            Bundle extras = new Bundle(1);
11567            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11568
11569            sendPackageBroadcast(
11570                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11571                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11572                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11573                    new int[] {userId});
11574        }
11575    }
11576
11577    /**
11578     * Returns true if application is not found or there was an error. Otherwise it returns
11579     * the hidden state of the package for the given user.
11580     */
11581    @Override
11582    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11583        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11584        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11585                true /* requireFullPermission */, false /* checkShell */,
11586                "getApplicationHidden for user " + userId);
11587        PackageSetting pkgSetting;
11588        long callingId = Binder.clearCallingIdentity();
11589        try {
11590            // writer
11591            synchronized (mPackages) {
11592                pkgSetting = mSettings.mPackages.get(packageName);
11593                if (pkgSetting == null) {
11594                    return true;
11595                }
11596                return pkgSetting.getHidden(userId);
11597            }
11598        } finally {
11599            Binder.restoreCallingIdentity(callingId);
11600        }
11601    }
11602
11603    /**
11604     * @hide
11605     */
11606    @Override
11607    public int installExistingPackageAsUser(String packageName, int userId) {
11608        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11609                null);
11610        PackageSetting pkgSetting;
11611        final int uid = Binder.getCallingUid();
11612        enforceCrossUserPermission(uid, userId,
11613                true /* requireFullPermission */, true /* checkShell */,
11614                "installExistingPackage for user " + userId);
11615        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11616            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11617        }
11618
11619        long callingId = Binder.clearCallingIdentity();
11620        try {
11621            boolean installed = false;
11622
11623            // writer
11624            synchronized (mPackages) {
11625                pkgSetting = mSettings.mPackages.get(packageName);
11626                if (pkgSetting == null) {
11627                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11628                }
11629                if (!pkgSetting.getInstalled(userId)) {
11630                    pkgSetting.setInstalled(true, userId);
11631                    pkgSetting.setHidden(false, userId);
11632                    mSettings.writePackageRestrictionsLPr(userId);
11633                    installed = true;
11634                }
11635            }
11636
11637            if (installed) {
11638                if (pkgSetting.pkg != null) {
11639                    synchronized (mInstallLock) {
11640                        // We don't need to freeze for a brand new install
11641                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11642                    }
11643                }
11644                sendPackageAddedForUser(packageName, pkgSetting, userId);
11645            }
11646        } finally {
11647            Binder.restoreCallingIdentity(callingId);
11648        }
11649
11650        return PackageManager.INSTALL_SUCCEEDED;
11651    }
11652
11653    boolean isUserRestricted(int userId, String restrictionKey) {
11654        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11655        if (restrictions.getBoolean(restrictionKey, false)) {
11656            Log.w(TAG, "User is restricted: " + restrictionKey);
11657            return true;
11658        }
11659        return false;
11660    }
11661
11662    @Override
11663    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11664            int userId) {
11665        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11666        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11667                true /* requireFullPermission */, true /* checkShell */,
11668                "setPackagesSuspended for user " + userId);
11669
11670        if (ArrayUtils.isEmpty(packageNames)) {
11671            return packageNames;
11672        }
11673
11674        // List of package names for whom the suspended state has changed.
11675        List<String> changedPackages = new ArrayList<>(packageNames.length);
11676        // List of package names for whom the suspended state is not set as requested in this
11677        // method.
11678        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11679        long callingId = Binder.clearCallingIdentity();
11680        try {
11681            for (int i = 0; i < packageNames.length; i++) {
11682                String packageName = packageNames[i];
11683                boolean changed = false;
11684                final int appId;
11685                synchronized (mPackages) {
11686                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11687                    if (pkgSetting == null) {
11688                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11689                                + "\". Skipping suspending/un-suspending.");
11690                        unactionedPackages.add(packageName);
11691                        continue;
11692                    }
11693                    appId = pkgSetting.appId;
11694                    if (pkgSetting.getSuspended(userId) != suspended) {
11695                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11696                            unactionedPackages.add(packageName);
11697                            continue;
11698                        }
11699                        pkgSetting.setSuspended(suspended, userId);
11700                        mSettings.writePackageRestrictionsLPr(userId);
11701                        changed = true;
11702                        changedPackages.add(packageName);
11703                    }
11704                }
11705
11706                if (changed && suspended) {
11707                    killApplication(packageName, UserHandle.getUid(userId, appId),
11708                            "suspending package");
11709                }
11710            }
11711        } finally {
11712            Binder.restoreCallingIdentity(callingId);
11713        }
11714
11715        if (!changedPackages.isEmpty()) {
11716            sendPackagesSuspendedForUser(changedPackages.toArray(
11717                    new String[changedPackages.size()]), userId, suspended);
11718        }
11719
11720        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11721    }
11722
11723    @Override
11724    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11725        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11726                true /* requireFullPermission */, false /* checkShell */,
11727                "isPackageSuspendedForUser for user " + userId);
11728        synchronized (mPackages) {
11729            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11730            if (pkgSetting == null) {
11731                throw new IllegalArgumentException("Unknown target package: " + packageName);
11732            }
11733            return pkgSetting.getSuspended(userId);
11734        }
11735    }
11736
11737    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11738        if (isPackageDeviceAdmin(packageName, userId)) {
11739            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11740                    + "\": has an active device admin");
11741            return false;
11742        }
11743
11744        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11745        if (packageName.equals(activeLauncherPackageName)) {
11746            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11747                    + "\": contains the active launcher");
11748            return false;
11749        }
11750
11751        if (packageName.equals(mRequiredInstallerPackage)) {
11752            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11753                    + "\": required for package installation");
11754            return false;
11755        }
11756
11757        if (packageName.equals(mRequiredVerifierPackage)) {
11758            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11759                    + "\": required for package verification");
11760            return false;
11761        }
11762
11763        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11764            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11765                    + "\": is the default dialer");
11766            return false;
11767        }
11768
11769        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11770            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11771                    + "\": protected package");
11772            return false;
11773        }
11774
11775        return true;
11776    }
11777
11778    private String getActiveLauncherPackageName(int userId) {
11779        Intent intent = new Intent(Intent.ACTION_MAIN);
11780        intent.addCategory(Intent.CATEGORY_HOME);
11781        ResolveInfo resolveInfo = resolveIntent(
11782                intent,
11783                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11784                PackageManager.MATCH_DEFAULT_ONLY,
11785                userId);
11786
11787        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11788    }
11789
11790    private String getDefaultDialerPackageName(int userId) {
11791        synchronized (mPackages) {
11792            return mSettings.getDefaultDialerPackageNameLPw(userId);
11793        }
11794    }
11795
11796    @Override
11797    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11798        mContext.enforceCallingOrSelfPermission(
11799                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11800                "Only package verification agents can verify applications");
11801
11802        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11803        final PackageVerificationResponse response = new PackageVerificationResponse(
11804                verificationCode, Binder.getCallingUid());
11805        msg.arg1 = id;
11806        msg.obj = response;
11807        mHandler.sendMessage(msg);
11808    }
11809
11810    @Override
11811    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11812            long millisecondsToDelay) {
11813        mContext.enforceCallingOrSelfPermission(
11814                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11815                "Only package verification agents can extend verification timeouts");
11816
11817        final PackageVerificationState state = mPendingVerification.get(id);
11818        final PackageVerificationResponse response = new PackageVerificationResponse(
11819                verificationCodeAtTimeout, Binder.getCallingUid());
11820
11821        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11822            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11823        }
11824        if (millisecondsToDelay < 0) {
11825            millisecondsToDelay = 0;
11826        }
11827        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11828                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11829            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11830        }
11831
11832        if ((state != null) && !state.timeoutExtended()) {
11833            state.extendTimeout();
11834
11835            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11836            msg.arg1 = id;
11837            msg.obj = response;
11838            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11839        }
11840    }
11841
11842    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11843            int verificationCode, UserHandle user) {
11844        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11845        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11846        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11847        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11848        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11849
11850        mContext.sendBroadcastAsUser(intent, user,
11851                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11852    }
11853
11854    private ComponentName matchComponentForVerifier(String packageName,
11855            List<ResolveInfo> receivers) {
11856        ActivityInfo targetReceiver = null;
11857
11858        final int NR = receivers.size();
11859        for (int i = 0; i < NR; i++) {
11860            final ResolveInfo info = receivers.get(i);
11861            if (info.activityInfo == null) {
11862                continue;
11863            }
11864
11865            if (packageName.equals(info.activityInfo.packageName)) {
11866                targetReceiver = info.activityInfo;
11867                break;
11868            }
11869        }
11870
11871        if (targetReceiver == null) {
11872            return null;
11873        }
11874
11875        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11876    }
11877
11878    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11879            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11880        if (pkgInfo.verifiers.length == 0) {
11881            return null;
11882        }
11883
11884        final int N = pkgInfo.verifiers.length;
11885        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11886        for (int i = 0; i < N; i++) {
11887            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11888
11889            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11890                    receivers);
11891            if (comp == null) {
11892                continue;
11893            }
11894
11895            final int verifierUid = getUidForVerifier(verifierInfo);
11896            if (verifierUid == -1) {
11897                continue;
11898            }
11899
11900            if (DEBUG_VERIFY) {
11901                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11902                        + " with the correct signature");
11903            }
11904            sufficientVerifiers.add(comp);
11905            verificationState.addSufficientVerifier(verifierUid);
11906        }
11907
11908        return sufficientVerifiers;
11909    }
11910
11911    private int getUidForVerifier(VerifierInfo verifierInfo) {
11912        synchronized (mPackages) {
11913            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11914            if (pkg == null) {
11915                return -1;
11916            } else if (pkg.mSignatures.length != 1) {
11917                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11918                        + " has more than one signature; ignoring");
11919                return -1;
11920            }
11921
11922            /*
11923             * If the public key of the package's signature does not match
11924             * our expected public key, then this is a different package and
11925             * we should skip.
11926             */
11927
11928            final byte[] expectedPublicKey;
11929            try {
11930                final Signature verifierSig = pkg.mSignatures[0];
11931                final PublicKey publicKey = verifierSig.getPublicKey();
11932                expectedPublicKey = publicKey.getEncoded();
11933            } catch (CertificateException e) {
11934                return -1;
11935            }
11936
11937            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11938
11939            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11940                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11941                        + " does not have the expected public key; ignoring");
11942                return -1;
11943            }
11944
11945            return pkg.applicationInfo.uid;
11946        }
11947    }
11948
11949    @Override
11950    public void finishPackageInstall(int token, boolean didLaunch) {
11951        enforceSystemOrRoot("Only the system is allowed to finish installs");
11952
11953        if (DEBUG_INSTALL) {
11954            Slog.v(TAG, "BM finishing package install for " + token);
11955        }
11956        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11957
11958        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
11959        mHandler.sendMessage(msg);
11960    }
11961
11962    /**
11963     * Get the verification agent timeout.
11964     *
11965     * @return verification timeout in milliseconds
11966     */
11967    private long getVerificationTimeout() {
11968        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11969                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11970                DEFAULT_VERIFICATION_TIMEOUT);
11971    }
11972
11973    /**
11974     * Get the default verification agent response code.
11975     *
11976     * @return default verification response code
11977     */
11978    private int getDefaultVerificationResponse() {
11979        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11980                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11981                DEFAULT_VERIFICATION_RESPONSE);
11982    }
11983
11984    /**
11985     * Check whether or not package verification has been enabled.
11986     *
11987     * @return true if verification should be performed
11988     */
11989    private boolean isVerificationEnabled(int userId, int installFlags) {
11990        if (!DEFAULT_VERIFY_ENABLE) {
11991            return false;
11992        }
11993        // Ephemeral apps don't get the full verification treatment
11994        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11995            if (DEBUG_EPHEMERAL) {
11996                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11997            }
11998            return false;
11999        }
12000
12001        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12002
12003        // Check if installing from ADB
12004        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12005            // Do not run verification in a test harness environment
12006            if (ActivityManager.isRunningInTestHarness()) {
12007                return false;
12008            }
12009            if (ensureVerifyAppsEnabled) {
12010                return true;
12011            }
12012            // Check if the developer does not want package verification for ADB installs
12013            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12014                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12015                return false;
12016            }
12017        }
12018
12019        if (ensureVerifyAppsEnabled) {
12020            return true;
12021        }
12022
12023        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12024                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12025    }
12026
12027    @Override
12028    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12029            throws RemoteException {
12030        mContext.enforceCallingOrSelfPermission(
12031                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12032                "Only intentfilter verification agents can verify applications");
12033
12034        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12035        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12036                Binder.getCallingUid(), verificationCode, failedDomains);
12037        msg.arg1 = id;
12038        msg.obj = response;
12039        mHandler.sendMessage(msg);
12040    }
12041
12042    @Override
12043    public int getIntentVerificationStatus(String packageName, int userId) {
12044        synchronized (mPackages) {
12045            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12046        }
12047    }
12048
12049    @Override
12050    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12051        mContext.enforceCallingOrSelfPermission(
12052                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12053
12054        boolean result = false;
12055        synchronized (mPackages) {
12056            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12057        }
12058        if (result) {
12059            scheduleWritePackageRestrictionsLocked(userId);
12060        }
12061        return result;
12062    }
12063
12064    @Override
12065    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12066            String packageName) {
12067        synchronized (mPackages) {
12068            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12069        }
12070    }
12071
12072    @Override
12073    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12074        if (TextUtils.isEmpty(packageName)) {
12075            return ParceledListSlice.emptyList();
12076        }
12077        synchronized (mPackages) {
12078            PackageParser.Package pkg = mPackages.get(packageName);
12079            if (pkg == null || pkg.activities == null) {
12080                return ParceledListSlice.emptyList();
12081            }
12082            final int count = pkg.activities.size();
12083            ArrayList<IntentFilter> result = new ArrayList<>();
12084            for (int n=0; n<count; n++) {
12085                PackageParser.Activity activity = pkg.activities.get(n);
12086                if (activity.intents != null && activity.intents.size() > 0) {
12087                    result.addAll(activity.intents);
12088                }
12089            }
12090            return new ParceledListSlice<>(result);
12091        }
12092    }
12093
12094    @Override
12095    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12096        mContext.enforceCallingOrSelfPermission(
12097                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12098
12099        synchronized (mPackages) {
12100            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12101            if (packageName != null) {
12102                result |= updateIntentVerificationStatus(packageName,
12103                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12104                        userId);
12105                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12106                        packageName, userId);
12107            }
12108            return result;
12109        }
12110    }
12111
12112    @Override
12113    public String getDefaultBrowserPackageName(int userId) {
12114        synchronized (mPackages) {
12115            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12116        }
12117    }
12118
12119    /**
12120     * Get the "allow unknown sources" setting.
12121     *
12122     * @return the current "allow unknown sources" setting
12123     */
12124    private int getUnknownSourcesSettings() {
12125        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12126                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12127                -1);
12128    }
12129
12130    @Override
12131    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12132        final int uid = Binder.getCallingUid();
12133        // writer
12134        synchronized (mPackages) {
12135            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12136            if (targetPackageSetting == null) {
12137                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12138            }
12139
12140            PackageSetting installerPackageSetting;
12141            if (installerPackageName != null) {
12142                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12143                if (installerPackageSetting == null) {
12144                    throw new IllegalArgumentException("Unknown installer package: "
12145                            + installerPackageName);
12146                }
12147            } else {
12148                installerPackageSetting = null;
12149            }
12150
12151            Signature[] callerSignature;
12152            Object obj = mSettings.getUserIdLPr(uid);
12153            if (obj != null) {
12154                if (obj instanceof SharedUserSetting) {
12155                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12156                } else if (obj instanceof PackageSetting) {
12157                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12158                } else {
12159                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12160                }
12161            } else {
12162                throw new SecurityException("Unknown calling UID: " + uid);
12163            }
12164
12165            // Verify: can't set installerPackageName to a package that is
12166            // not signed with the same cert as the caller.
12167            if (installerPackageSetting != null) {
12168                if (compareSignatures(callerSignature,
12169                        installerPackageSetting.signatures.mSignatures)
12170                        != PackageManager.SIGNATURE_MATCH) {
12171                    throw new SecurityException(
12172                            "Caller does not have same cert as new installer package "
12173                            + installerPackageName);
12174                }
12175            }
12176
12177            // Verify: if target already has an installer package, it must
12178            // be signed with the same cert as the caller.
12179            if (targetPackageSetting.installerPackageName != null) {
12180                PackageSetting setting = mSettings.mPackages.get(
12181                        targetPackageSetting.installerPackageName);
12182                // If the currently set package isn't valid, then it's always
12183                // okay to change it.
12184                if (setting != null) {
12185                    if (compareSignatures(callerSignature,
12186                            setting.signatures.mSignatures)
12187                            != PackageManager.SIGNATURE_MATCH) {
12188                        throw new SecurityException(
12189                                "Caller does not have same cert as old installer package "
12190                                + targetPackageSetting.installerPackageName);
12191                    }
12192                }
12193            }
12194
12195            // Okay!
12196            targetPackageSetting.installerPackageName = installerPackageName;
12197            if (installerPackageName != null) {
12198                mSettings.mInstallerPackages.add(installerPackageName);
12199            }
12200            scheduleWriteSettingsLocked();
12201        }
12202    }
12203
12204    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12205        // Queue up an async operation since the package installation may take a little while.
12206        mHandler.post(new Runnable() {
12207            public void run() {
12208                mHandler.removeCallbacks(this);
12209                 // Result object to be returned
12210                PackageInstalledInfo res = new PackageInstalledInfo();
12211                res.setReturnCode(currentStatus);
12212                res.uid = -1;
12213                res.pkg = null;
12214                res.removedInfo = null;
12215                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12216                    args.doPreInstall(res.returnCode);
12217                    synchronized (mInstallLock) {
12218                        installPackageTracedLI(args, res);
12219                    }
12220                    args.doPostInstall(res.returnCode, res.uid);
12221                }
12222
12223                // A restore should be performed at this point if (a) the install
12224                // succeeded, (b) the operation is not an update, and (c) the new
12225                // package has not opted out of backup participation.
12226                final boolean update = res.removedInfo != null
12227                        && res.removedInfo.removedPackage != null;
12228                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12229                boolean doRestore = !update
12230                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12231
12232                // Set up the post-install work request bookkeeping.  This will be used
12233                // and cleaned up by the post-install event handling regardless of whether
12234                // there's a restore pass performed.  Token values are >= 1.
12235                int token;
12236                if (mNextInstallToken < 0) mNextInstallToken = 1;
12237                token = mNextInstallToken++;
12238
12239                PostInstallData data = new PostInstallData(args, res);
12240                mRunningInstalls.put(token, data);
12241                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12242
12243                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12244                    // Pass responsibility to the Backup Manager.  It will perform a
12245                    // restore if appropriate, then pass responsibility back to the
12246                    // Package Manager to run the post-install observer callbacks
12247                    // and broadcasts.
12248                    IBackupManager bm = IBackupManager.Stub.asInterface(
12249                            ServiceManager.getService(Context.BACKUP_SERVICE));
12250                    if (bm != null) {
12251                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12252                                + " to BM for possible restore");
12253                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12254                        try {
12255                            // TODO: http://b/22388012
12256                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12257                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12258                            } else {
12259                                doRestore = false;
12260                            }
12261                        } catch (RemoteException e) {
12262                            // can't happen; the backup manager is local
12263                        } catch (Exception e) {
12264                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12265                            doRestore = false;
12266                        }
12267                    } else {
12268                        Slog.e(TAG, "Backup Manager not found!");
12269                        doRestore = false;
12270                    }
12271                }
12272
12273                if (!doRestore) {
12274                    // No restore possible, or the Backup Manager was mysteriously not
12275                    // available -- just fire the post-install work request directly.
12276                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12277
12278                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12279
12280                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12281                    mHandler.sendMessage(msg);
12282                }
12283            }
12284        });
12285    }
12286
12287    /**
12288     * Callback from PackageSettings whenever an app is first transitioned out of the
12289     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12290     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12291     * here whether the app is the target of an ongoing install, and only send the
12292     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12293     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12294     * handling.
12295     */
12296    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12297        // Serialize this with the rest of the install-process message chain.  In the
12298        // restore-at-install case, this Runnable will necessarily run before the
12299        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12300        // are coherent.  In the non-restore case, the app has already completed install
12301        // and been launched through some other means, so it is not in a problematic
12302        // state for observers to see the FIRST_LAUNCH signal.
12303        mHandler.post(new Runnable() {
12304            @Override
12305            public void run() {
12306                for (int i = 0; i < mRunningInstalls.size(); i++) {
12307                    final PostInstallData data = mRunningInstalls.valueAt(i);
12308                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12309                        continue;
12310                    }
12311                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12312                        // right package; but is it for the right user?
12313                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12314                            if (userId == data.res.newUsers[uIndex]) {
12315                                if (DEBUG_BACKUP) {
12316                                    Slog.i(TAG, "Package " + pkgName
12317                                            + " being restored so deferring FIRST_LAUNCH");
12318                                }
12319                                return;
12320                            }
12321                        }
12322                    }
12323                }
12324                // didn't find it, so not being restored
12325                if (DEBUG_BACKUP) {
12326                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12327                }
12328                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12329            }
12330        });
12331    }
12332
12333    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12334        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12335                installerPkg, null, userIds);
12336    }
12337
12338    private abstract class HandlerParams {
12339        private static final int MAX_RETRIES = 4;
12340
12341        /**
12342         * Number of times startCopy() has been attempted and had a non-fatal
12343         * error.
12344         */
12345        private int mRetries = 0;
12346
12347        /** User handle for the user requesting the information or installation. */
12348        private final UserHandle mUser;
12349        String traceMethod;
12350        int traceCookie;
12351
12352        HandlerParams(UserHandle user) {
12353            mUser = user;
12354        }
12355
12356        UserHandle getUser() {
12357            return mUser;
12358        }
12359
12360        HandlerParams setTraceMethod(String traceMethod) {
12361            this.traceMethod = traceMethod;
12362            return this;
12363        }
12364
12365        HandlerParams setTraceCookie(int traceCookie) {
12366            this.traceCookie = traceCookie;
12367            return this;
12368        }
12369
12370        final boolean startCopy() {
12371            boolean res;
12372            try {
12373                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12374
12375                if (++mRetries > MAX_RETRIES) {
12376                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12377                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12378                    handleServiceError();
12379                    return false;
12380                } else {
12381                    handleStartCopy();
12382                    res = true;
12383                }
12384            } catch (RemoteException e) {
12385                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12386                mHandler.sendEmptyMessage(MCS_RECONNECT);
12387                res = false;
12388            }
12389            handleReturnCode();
12390            return res;
12391        }
12392
12393        final void serviceError() {
12394            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12395            handleServiceError();
12396            handleReturnCode();
12397        }
12398
12399        abstract void handleStartCopy() throws RemoteException;
12400        abstract void handleServiceError();
12401        abstract void handleReturnCode();
12402    }
12403
12404    class MeasureParams extends HandlerParams {
12405        private final PackageStats mStats;
12406        private boolean mSuccess;
12407
12408        private final IPackageStatsObserver mObserver;
12409
12410        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12411            super(new UserHandle(stats.userHandle));
12412            mObserver = observer;
12413            mStats = stats;
12414        }
12415
12416        @Override
12417        public String toString() {
12418            return "MeasureParams{"
12419                + Integer.toHexString(System.identityHashCode(this))
12420                + " " + mStats.packageName + "}";
12421        }
12422
12423        @Override
12424        void handleStartCopy() throws RemoteException {
12425            synchronized (mInstallLock) {
12426                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12427            }
12428
12429            if (mSuccess) {
12430                boolean mounted = false;
12431                try {
12432                    final String status = Environment.getExternalStorageState();
12433                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12434                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12435                } catch (Exception e) {
12436                }
12437
12438                if (mounted) {
12439                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12440
12441                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12442                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12443
12444                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12445                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12446
12447                    // Always subtract cache size, since it's a subdirectory
12448                    mStats.externalDataSize -= mStats.externalCacheSize;
12449
12450                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12451                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12452
12453                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12454                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12455                }
12456            }
12457        }
12458
12459        @Override
12460        void handleReturnCode() {
12461            if (mObserver != null) {
12462                try {
12463                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12464                } catch (RemoteException e) {
12465                    Slog.i(TAG, "Observer no longer exists.");
12466                }
12467            }
12468        }
12469
12470        @Override
12471        void handleServiceError() {
12472            Slog.e(TAG, "Could not measure application " + mStats.packageName
12473                            + " external storage");
12474        }
12475    }
12476
12477    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12478            throws RemoteException {
12479        long result = 0;
12480        for (File path : paths) {
12481            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12482        }
12483        return result;
12484    }
12485
12486    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12487        for (File path : paths) {
12488            try {
12489                mcs.clearDirectory(path.getAbsolutePath());
12490            } catch (RemoteException e) {
12491            }
12492        }
12493    }
12494
12495    static class OriginInfo {
12496        /**
12497         * Location where install is coming from, before it has been
12498         * copied/renamed into place. This could be a single monolithic APK
12499         * file, or a cluster directory. This location may be untrusted.
12500         */
12501        final File file;
12502        final String cid;
12503
12504        /**
12505         * Flag indicating that {@link #file} or {@link #cid} has already been
12506         * staged, meaning downstream users don't need to defensively copy the
12507         * contents.
12508         */
12509        final boolean staged;
12510
12511        /**
12512         * Flag indicating that {@link #file} or {@link #cid} is an already
12513         * installed app that is being moved.
12514         */
12515        final boolean existing;
12516
12517        final String resolvedPath;
12518        final File resolvedFile;
12519
12520        static OriginInfo fromNothing() {
12521            return new OriginInfo(null, null, false, false);
12522        }
12523
12524        static OriginInfo fromUntrustedFile(File file) {
12525            return new OriginInfo(file, null, false, false);
12526        }
12527
12528        static OriginInfo fromExistingFile(File file) {
12529            return new OriginInfo(file, null, false, true);
12530        }
12531
12532        static OriginInfo fromStagedFile(File file) {
12533            return new OriginInfo(file, null, true, false);
12534        }
12535
12536        static OriginInfo fromStagedContainer(String cid) {
12537            return new OriginInfo(null, cid, true, false);
12538        }
12539
12540        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12541            this.file = file;
12542            this.cid = cid;
12543            this.staged = staged;
12544            this.existing = existing;
12545
12546            if (cid != null) {
12547                resolvedPath = PackageHelper.getSdDir(cid);
12548                resolvedFile = new File(resolvedPath);
12549            } else if (file != null) {
12550                resolvedPath = file.getAbsolutePath();
12551                resolvedFile = file;
12552            } else {
12553                resolvedPath = null;
12554                resolvedFile = null;
12555            }
12556        }
12557    }
12558
12559    static class MoveInfo {
12560        final int moveId;
12561        final String fromUuid;
12562        final String toUuid;
12563        final String packageName;
12564        final String dataAppName;
12565        final int appId;
12566        final String seinfo;
12567        final int targetSdkVersion;
12568
12569        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12570                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12571            this.moveId = moveId;
12572            this.fromUuid = fromUuid;
12573            this.toUuid = toUuid;
12574            this.packageName = packageName;
12575            this.dataAppName = dataAppName;
12576            this.appId = appId;
12577            this.seinfo = seinfo;
12578            this.targetSdkVersion = targetSdkVersion;
12579        }
12580    }
12581
12582    static class VerificationInfo {
12583        /** A constant used to indicate that a uid value is not present. */
12584        public static final int NO_UID = -1;
12585
12586        /** URI referencing where the package was downloaded from. */
12587        final Uri originatingUri;
12588
12589        /** HTTP referrer URI associated with the originatingURI. */
12590        final Uri referrer;
12591
12592        /** UID of the application that the install request originated from. */
12593        final int originatingUid;
12594
12595        /** UID of application requesting the install */
12596        final int installerUid;
12597
12598        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12599            this.originatingUri = originatingUri;
12600            this.referrer = referrer;
12601            this.originatingUid = originatingUid;
12602            this.installerUid = installerUid;
12603        }
12604    }
12605
12606    class InstallParams extends HandlerParams {
12607        final OriginInfo origin;
12608        final MoveInfo move;
12609        final IPackageInstallObserver2 observer;
12610        int installFlags;
12611        final String installerPackageName;
12612        final String volumeUuid;
12613        private InstallArgs mArgs;
12614        private int mRet;
12615        final String packageAbiOverride;
12616        final String[] grantedRuntimePermissions;
12617        final VerificationInfo verificationInfo;
12618        final Certificate[][] certificates;
12619
12620        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12621                int installFlags, String installerPackageName, String volumeUuid,
12622                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12623                String[] grantedPermissions, Certificate[][] certificates) {
12624            super(user);
12625            this.origin = origin;
12626            this.move = move;
12627            this.observer = observer;
12628            this.installFlags = installFlags;
12629            this.installerPackageName = installerPackageName;
12630            this.volumeUuid = volumeUuid;
12631            this.verificationInfo = verificationInfo;
12632            this.packageAbiOverride = packageAbiOverride;
12633            this.grantedRuntimePermissions = grantedPermissions;
12634            this.certificates = certificates;
12635        }
12636
12637        @Override
12638        public String toString() {
12639            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12640                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12641        }
12642
12643        private int installLocationPolicy(PackageInfoLite pkgLite) {
12644            String packageName = pkgLite.packageName;
12645            int installLocation = pkgLite.installLocation;
12646            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12647            // reader
12648            synchronized (mPackages) {
12649                // Currently installed package which the new package is attempting to replace or
12650                // null if no such package is installed.
12651                PackageParser.Package installedPkg = mPackages.get(packageName);
12652                // Package which currently owns the data which the new package will own if installed.
12653                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12654                // will be null whereas dataOwnerPkg will contain information about the package
12655                // which was uninstalled while keeping its data.
12656                PackageParser.Package dataOwnerPkg = installedPkg;
12657                if (dataOwnerPkg  == null) {
12658                    PackageSetting ps = mSettings.mPackages.get(packageName);
12659                    if (ps != null) {
12660                        dataOwnerPkg = ps.pkg;
12661                    }
12662                }
12663
12664                if (dataOwnerPkg != null) {
12665                    // If installed, the package will get access to data left on the device by its
12666                    // predecessor. As a security measure, this is permited only if this is not a
12667                    // version downgrade or if the predecessor package is marked as debuggable and
12668                    // a downgrade is explicitly requested.
12669                    //
12670                    // On debuggable platform builds, downgrades are permitted even for
12671                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12672                    // not offer security guarantees and thus it's OK to disable some security
12673                    // mechanisms to make debugging/testing easier on those builds. However, even on
12674                    // debuggable builds downgrades of packages are permitted only if requested via
12675                    // installFlags. This is because we aim to keep the behavior of debuggable
12676                    // platform builds as close as possible to the behavior of non-debuggable
12677                    // platform builds.
12678                    final boolean downgradeRequested =
12679                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12680                    final boolean packageDebuggable =
12681                                (dataOwnerPkg.applicationInfo.flags
12682                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12683                    final boolean downgradePermitted =
12684                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12685                    if (!downgradePermitted) {
12686                        try {
12687                            checkDowngrade(dataOwnerPkg, pkgLite);
12688                        } catch (PackageManagerException e) {
12689                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12690                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12691                        }
12692                    }
12693                }
12694
12695                if (installedPkg != null) {
12696                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12697                        // Check for updated system application.
12698                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12699                            if (onSd) {
12700                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12701                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12702                            }
12703                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12704                        } else {
12705                            if (onSd) {
12706                                // Install flag overrides everything.
12707                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12708                            }
12709                            // If current upgrade specifies particular preference
12710                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12711                                // Application explicitly specified internal.
12712                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12713                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12714                                // App explictly prefers external. Let policy decide
12715                            } else {
12716                                // Prefer previous location
12717                                if (isExternal(installedPkg)) {
12718                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12719                                }
12720                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12721                            }
12722                        }
12723                    } else {
12724                        // Invalid install. Return error code
12725                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12726                    }
12727                }
12728            }
12729            // All the special cases have been taken care of.
12730            // Return result based on recommended install location.
12731            if (onSd) {
12732                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12733            }
12734            return pkgLite.recommendedInstallLocation;
12735        }
12736
12737        /*
12738         * Invoke remote method to get package information and install
12739         * location values. Override install location based on default
12740         * policy if needed and then create install arguments based
12741         * on the install location.
12742         */
12743        public void handleStartCopy() throws RemoteException {
12744            int ret = PackageManager.INSTALL_SUCCEEDED;
12745
12746            // If we're already staged, we've firmly committed to an install location
12747            if (origin.staged) {
12748                if (origin.file != null) {
12749                    installFlags |= PackageManager.INSTALL_INTERNAL;
12750                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12751                } else if (origin.cid != null) {
12752                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12753                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12754                } else {
12755                    throw new IllegalStateException("Invalid stage location");
12756                }
12757            }
12758
12759            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12760            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12761            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12762            PackageInfoLite pkgLite = null;
12763
12764            if (onInt && onSd) {
12765                // Check if both bits are set.
12766                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12767                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12768            } else if (onSd && ephemeral) {
12769                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12770                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12771            } else {
12772                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12773                        packageAbiOverride);
12774
12775                if (DEBUG_EPHEMERAL && ephemeral) {
12776                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12777                }
12778
12779                /*
12780                 * If we have too little free space, try to free cache
12781                 * before giving up.
12782                 */
12783                if (!origin.staged && pkgLite.recommendedInstallLocation
12784                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12785                    // TODO: focus freeing disk space on the target device
12786                    final StorageManager storage = StorageManager.from(mContext);
12787                    final long lowThreshold = storage.getStorageLowBytes(
12788                            Environment.getDataDirectory());
12789
12790                    final long sizeBytes = mContainerService.calculateInstalledSize(
12791                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12792
12793                    try {
12794                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12795                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12796                                installFlags, packageAbiOverride);
12797                    } catch (InstallerException e) {
12798                        Slog.w(TAG, "Failed to free cache", e);
12799                    }
12800
12801                    /*
12802                     * The cache free must have deleted the file we
12803                     * downloaded to install.
12804                     *
12805                     * TODO: fix the "freeCache" call to not delete
12806                     *       the file we care about.
12807                     */
12808                    if (pkgLite.recommendedInstallLocation
12809                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12810                        pkgLite.recommendedInstallLocation
12811                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12812                    }
12813                }
12814            }
12815
12816            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12817                int loc = pkgLite.recommendedInstallLocation;
12818                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12819                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12820                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12821                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12822                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12823                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12824                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12825                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12826                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12827                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12828                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12829                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12830                } else {
12831                    // Override with defaults if needed.
12832                    loc = installLocationPolicy(pkgLite);
12833                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12834                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12835                    } else if (!onSd && !onInt) {
12836                        // Override install location with flags
12837                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12838                            // Set the flag to install on external media.
12839                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12840                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12841                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12842                            if (DEBUG_EPHEMERAL) {
12843                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12844                            }
12845                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12846                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12847                                    |PackageManager.INSTALL_INTERNAL);
12848                        } else {
12849                            // Make sure the flag for installing on external
12850                            // media is unset
12851                            installFlags |= PackageManager.INSTALL_INTERNAL;
12852                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12853                        }
12854                    }
12855                }
12856            }
12857
12858            final InstallArgs args = createInstallArgs(this);
12859            mArgs = args;
12860
12861            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12862                // TODO: http://b/22976637
12863                // Apps installed for "all" users use the device owner to verify the app
12864                UserHandle verifierUser = getUser();
12865                if (verifierUser == UserHandle.ALL) {
12866                    verifierUser = UserHandle.SYSTEM;
12867                }
12868
12869                /*
12870                 * Determine if we have any installed package verifiers. If we
12871                 * do, then we'll defer to them to verify the packages.
12872                 */
12873                final int requiredUid = mRequiredVerifierPackage == null ? -1
12874                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12875                                verifierUser.getIdentifier());
12876                if (!origin.existing && requiredUid != -1
12877                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12878                    final Intent verification = new Intent(
12879                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12880                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12881                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12882                            PACKAGE_MIME_TYPE);
12883                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12884
12885                    // Query all live verifiers based on current user state
12886                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12887                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12888
12889                    if (DEBUG_VERIFY) {
12890                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12891                                + verification.toString() + " with " + pkgLite.verifiers.length
12892                                + " optional verifiers");
12893                    }
12894
12895                    final int verificationId = mPendingVerificationToken++;
12896
12897                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12898
12899                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12900                            installerPackageName);
12901
12902                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12903                            installFlags);
12904
12905                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12906                            pkgLite.packageName);
12907
12908                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12909                            pkgLite.versionCode);
12910
12911                    if (verificationInfo != null) {
12912                        if (verificationInfo.originatingUri != null) {
12913                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12914                                    verificationInfo.originatingUri);
12915                        }
12916                        if (verificationInfo.referrer != null) {
12917                            verification.putExtra(Intent.EXTRA_REFERRER,
12918                                    verificationInfo.referrer);
12919                        }
12920                        if (verificationInfo.originatingUid >= 0) {
12921                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12922                                    verificationInfo.originatingUid);
12923                        }
12924                        if (verificationInfo.installerUid >= 0) {
12925                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12926                                    verificationInfo.installerUid);
12927                        }
12928                    }
12929
12930                    final PackageVerificationState verificationState = new PackageVerificationState(
12931                            requiredUid, args);
12932
12933                    mPendingVerification.append(verificationId, verificationState);
12934
12935                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12936                            receivers, verificationState);
12937
12938                    /*
12939                     * If any sufficient verifiers were listed in the package
12940                     * manifest, attempt to ask them.
12941                     */
12942                    if (sufficientVerifiers != null) {
12943                        final int N = sufficientVerifiers.size();
12944                        if (N == 0) {
12945                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12946                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12947                        } else {
12948                            for (int i = 0; i < N; i++) {
12949                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12950
12951                                final Intent sufficientIntent = new Intent(verification);
12952                                sufficientIntent.setComponent(verifierComponent);
12953                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12954                            }
12955                        }
12956                    }
12957
12958                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12959                            mRequiredVerifierPackage, receivers);
12960                    if (ret == PackageManager.INSTALL_SUCCEEDED
12961                            && mRequiredVerifierPackage != null) {
12962                        Trace.asyncTraceBegin(
12963                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12964                        /*
12965                         * Send the intent to the required verification agent,
12966                         * but only start the verification timeout after the
12967                         * target BroadcastReceivers have run.
12968                         */
12969                        verification.setComponent(requiredVerifierComponent);
12970                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12971                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12972                                new BroadcastReceiver() {
12973                                    @Override
12974                                    public void onReceive(Context context, Intent intent) {
12975                                        final Message msg = mHandler
12976                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12977                                        msg.arg1 = verificationId;
12978                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12979                                    }
12980                                }, null, 0, null, null);
12981
12982                        /*
12983                         * We don't want the copy to proceed until verification
12984                         * succeeds, so null out this field.
12985                         */
12986                        mArgs = null;
12987                    }
12988                } else {
12989                    /*
12990                     * No package verification is enabled, so immediately start
12991                     * the remote call to initiate copy using temporary file.
12992                     */
12993                    ret = args.copyApk(mContainerService, true);
12994                }
12995            }
12996
12997            mRet = ret;
12998        }
12999
13000        @Override
13001        void handleReturnCode() {
13002            // If mArgs is null, then MCS couldn't be reached. When it
13003            // reconnects, it will try again to install. At that point, this
13004            // will succeed.
13005            if (mArgs != null) {
13006                processPendingInstall(mArgs, mRet);
13007            }
13008        }
13009
13010        @Override
13011        void handleServiceError() {
13012            mArgs = createInstallArgs(this);
13013            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13014        }
13015
13016        public boolean isForwardLocked() {
13017            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13018        }
13019    }
13020
13021    /**
13022     * Used during creation of InstallArgs
13023     *
13024     * @param installFlags package installation flags
13025     * @return true if should be installed on external storage
13026     */
13027    private static boolean installOnExternalAsec(int installFlags) {
13028        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13029            return false;
13030        }
13031        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13032            return true;
13033        }
13034        return false;
13035    }
13036
13037    /**
13038     * Used during creation of InstallArgs
13039     *
13040     * @param installFlags package installation flags
13041     * @return true if should be installed as forward locked
13042     */
13043    private static boolean installForwardLocked(int installFlags) {
13044        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13045    }
13046
13047    private InstallArgs createInstallArgs(InstallParams params) {
13048        if (params.move != null) {
13049            return new MoveInstallArgs(params);
13050        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13051            return new AsecInstallArgs(params);
13052        } else {
13053            return new FileInstallArgs(params);
13054        }
13055    }
13056
13057    /**
13058     * Create args that describe an existing installed package. Typically used
13059     * when cleaning up old installs, or used as a move source.
13060     */
13061    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13062            String resourcePath, String[] instructionSets) {
13063        final boolean isInAsec;
13064        if (installOnExternalAsec(installFlags)) {
13065            /* Apps on SD card are always in ASEC containers. */
13066            isInAsec = true;
13067        } else if (installForwardLocked(installFlags)
13068                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13069            /*
13070             * Forward-locked apps are only in ASEC containers if they're the
13071             * new style
13072             */
13073            isInAsec = true;
13074        } else {
13075            isInAsec = false;
13076        }
13077
13078        if (isInAsec) {
13079            return new AsecInstallArgs(codePath, instructionSets,
13080                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13081        } else {
13082            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13083        }
13084    }
13085
13086    static abstract class InstallArgs {
13087        /** @see InstallParams#origin */
13088        final OriginInfo origin;
13089        /** @see InstallParams#move */
13090        final MoveInfo move;
13091
13092        final IPackageInstallObserver2 observer;
13093        // Always refers to PackageManager flags only
13094        final int installFlags;
13095        final String installerPackageName;
13096        final String volumeUuid;
13097        final UserHandle user;
13098        final String abiOverride;
13099        final String[] installGrantPermissions;
13100        /** If non-null, drop an async trace when the install completes */
13101        final String traceMethod;
13102        final int traceCookie;
13103        final Certificate[][] certificates;
13104
13105        // The list of instruction sets supported by this app. This is currently
13106        // only used during the rmdex() phase to clean up resources. We can get rid of this
13107        // if we move dex files under the common app path.
13108        /* nullable */ String[] instructionSets;
13109
13110        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13111                int installFlags, String installerPackageName, String volumeUuid,
13112                UserHandle user, String[] instructionSets,
13113                String abiOverride, String[] installGrantPermissions,
13114                String traceMethod, int traceCookie, Certificate[][] certificates) {
13115            this.origin = origin;
13116            this.move = move;
13117            this.installFlags = installFlags;
13118            this.observer = observer;
13119            this.installerPackageName = installerPackageName;
13120            this.volumeUuid = volumeUuid;
13121            this.user = user;
13122            this.instructionSets = instructionSets;
13123            this.abiOverride = abiOverride;
13124            this.installGrantPermissions = installGrantPermissions;
13125            this.traceMethod = traceMethod;
13126            this.traceCookie = traceCookie;
13127            this.certificates = certificates;
13128        }
13129
13130        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13131        abstract int doPreInstall(int status);
13132
13133        /**
13134         * Rename package into final resting place. All paths on the given
13135         * scanned package should be updated to reflect the rename.
13136         */
13137        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13138        abstract int doPostInstall(int status, int uid);
13139
13140        /** @see PackageSettingBase#codePathString */
13141        abstract String getCodePath();
13142        /** @see PackageSettingBase#resourcePathString */
13143        abstract String getResourcePath();
13144
13145        // Need installer lock especially for dex file removal.
13146        abstract void cleanUpResourcesLI();
13147        abstract boolean doPostDeleteLI(boolean delete);
13148
13149        /**
13150         * Called before the source arguments are copied. This is used mostly
13151         * for MoveParams when it needs to read the source file to put it in the
13152         * destination.
13153         */
13154        int doPreCopy() {
13155            return PackageManager.INSTALL_SUCCEEDED;
13156        }
13157
13158        /**
13159         * Called after the source arguments are copied. This is used mostly for
13160         * MoveParams when it needs to read the source file to put it in the
13161         * destination.
13162         */
13163        int doPostCopy(int uid) {
13164            return PackageManager.INSTALL_SUCCEEDED;
13165        }
13166
13167        protected boolean isFwdLocked() {
13168            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13169        }
13170
13171        protected boolean isExternalAsec() {
13172            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13173        }
13174
13175        protected boolean isEphemeral() {
13176            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13177        }
13178
13179        UserHandle getUser() {
13180            return user;
13181        }
13182    }
13183
13184    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13185        if (!allCodePaths.isEmpty()) {
13186            if (instructionSets == null) {
13187                throw new IllegalStateException("instructionSet == null");
13188            }
13189            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13190            for (String codePath : allCodePaths) {
13191                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13192                    try {
13193                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13194                    } catch (InstallerException ignored) {
13195                    }
13196                }
13197            }
13198        }
13199    }
13200
13201    /**
13202     * Logic to handle installation of non-ASEC applications, including copying
13203     * and renaming logic.
13204     */
13205    class FileInstallArgs extends InstallArgs {
13206        private File codeFile;
13207        private File resourceFile;
13208
13209        // Example topology:
13210        // /data/app/com.example/base.apk
13211        // /data/app/com.example/split_foo.apk
13212        // /data/app/com.example/lib/arm/libfoo.so
13213        // /data/app/com.example/lib/arm64/libfoo.so
13214        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13215
13216        /** New install */
13217        FileInstallArgs(InstallParams params) {
13218            super(params.origin, params.move, params.observer, params.installFlags,
13219                    params.installerPackageName, params.volumeUuid,
13220                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13221                    params.grantedRuntimePermissions,
13222                    params.traceMethod, params.traceCookie, params.certificates);
13223            if (isFwdLocked()) {
13224                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13225            }
13226        }
13227
13228        /** Existing install */
13229        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13230            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13231                    null, null, null, 0, null /*certificates*/);
13232            this.codeFile = (codePath != null) ? new File(codePath) : null;
13233            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13234        }
13235
13236        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13237            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13238            try {
13239                return doCopyApk(imcs, temp);
13240            } finally {
13241                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13242            }
13243        }
13244
13245        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13246            if (origin.staged) {
13247                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13248                codeFile = origin.file;
13249                resourceFile = origin.file;
13250                return PackageManager.INSTALL_SUCCEEDED;
13251            }
13252
13253            try {
13254                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13255                final File tempDir =
13256                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13257                codeFile = tempDir;
13258                resourceFile = tempDir;
13259            } catch (IOException e) {
13260                Slog.w(TAG, "Failed to create copy file: " + e);
13261                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13262            }
13263
13264            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13265                @Override
13266                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13267                    if (!FileUtils.isValidExtFilename(name)) {
13268                        throw new IllegalArgumentException("Invalid filename: " + name);
13269                    }
13270                    try {
13271                        final File file = new File(codeFile, name);
13272                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13273                                O_RDWR | O_CREAT, 0644);
13274                        Os.chmod(file.getAbsolutePath(), 0644);
13275                        return new ParcelFileDescriptor(fd);
13276                    } catch (ErrnoException e) {
13277                        throw new RemoteException("Failed to open: " + e.getMessage());
13278                    }
13279                }
13280            };
13281
13282            int ret = PackageManager.INSTALL_SUCCEEDED;
13283            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13284            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13285                Slog.e(TAG, "Failed to copy package");
13286                return ret;
13287            }
13288
13289            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13290            NativeLibraryHelper.Handle handle = null;
13291            try {
13292                handle = NativeLibraryHelper.Handle.create(codeFile);
13293                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13294                        abiOverride);
13295            } catch (IOException e) {
13296                Slog.e(TAG, "Copying native libraries failed", e);
13297                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13298            } finally {
13299                IoUtils.closeQuietly(handle);
13300            }
13301
13302            return ret;
13303        }
13304
13305        int doPreInstall(int status) {
13306            if (status != PackageManager.INSTALL_SUCCEEDED) {
13307                cleanUp();
13308            }
13309            return status;
13310        }
13311
13312        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13313            if (status != PackageManager.INSTALL_SUCCEEDED) {
13314                cleanUp();
13315                return false;
13316            }
13317
13318            final File targetDir = codeFile.getParentFile();
13319            final File beforeCodeFile = codeFile;
13320            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13321
13322            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13323            try {
13324                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13325            } catch (ErrnoException e) {
13326                Slog.w(TAG, "Failed to rename", e);
13327                return false;
13328            }
13329
13330            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13331                Slog.w(TAG, "Failed to restorecon");
13332                return false;
13333            }
13334
13335            // Reflect the rename internally
13336            codeFile = afterCodeFile;
13337            resourceFile = afterCodeFile;
13338
13339            // Reflect the rename in scanned details
13340            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13341            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13342                    afterCodeFile, pkg.baseCodePath));
13343            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13344                    afterCodeFile, pkg.splitCodePaths));
13345
13346            // Reflect the rename in app info
13347            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13348            pkg.setApplicationInfoCodePath(pkg.codePath);
13349            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13350            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13351            pkg.setApplicationInfoResourcePath(pkg.codePath);
13352            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13353            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13354
13355            return true;
13356        }
13357
13358        int doPostInstall(int status, int uid) {
13359            if (status != PackageManager.INSTALL_SUCCEEDED) {
13360                cleanUp();
13361            }
13362            return status;
13363        }
13364
13365        @Override
13366        String getCodePath() {
13367            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13368        }
13369
13370        @Override
13371        String getResourcePath() {
13372            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13373        }
13374
13375        private boolean cleanUp() {
13376            if (codeFile == null || !codeFile.exists()) {
13377                return false;
13378            }
13379
13380            removeCodePathLI(codeFile);
13381
13382            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13383                resourceFile.delete();
13384            }
13385
13386            return true;
13387        }
13388
13389        void cleanUpResourcesLI() {
13390            // Try enumerating all code paths before deleting
13391            List<String> allCodePaths = Collections.EMPTY_LIST;
13392            if (codeFile != null && codeFile.exists()) {
13393                try {
13394                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13395                    allCodePaths = pkg.getAllCodePaths();
13396                } catch (PackageParserException e) {
13397                    // Ignored; we tried our best
13398                }
13399            }
13400
13401            cleanUp();
13402            removeDexFiles(allCodePaths, instructionSets);
13403        }
13404
13405        boolean doPostDeleteLI(boolean delete) {
13406            // XXX err, shouldn't we respect the delete flag?
13407            cleanUpResourcesLI();
13408            return true;
13409        }
13410    }
13411
13412    private boolean isAsecExternal(String cid) {
13413        final String asecPath = PackageHelper.getSdFilesystem(cid);
13414        return !asecPath.startsWith(mAsecInternalPath);
13415    }
13416
13417    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13418            PackageManagerException {
13419        if (copyRet < 0) {
13420            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13421                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13422                throw new PackageManagerException(copyRet, message);
13423            }
13424        }
13425    }
13426
13427    /**
13428     * Extract the MountService "container ID" from the full code path of an
13429     * .apk.
13430     */
13431    static String cidFromCodePath(String fullCodePath) {
13432        int eidx = fullCodePath.lastIndexOf("/");
13433        String subStr1 = fullCodePath.substring(0, eidx);
13434        int sidx = subStr1.lastIndexOf("/");
13435        return subStr1.substring(sidx+1, eidx);
13436    }
13437
13438    /**
13439     * Logic to handle installation of ASEC applications, including copying and
13440     * renaming logic.
13441     */
13442    class AsecInstallArgs extends InstallArgs {
13443        static final String RES_FILE_NAME = "pkg.apk";
13444        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13445
13446        String cid;
13447        String packagePath;
13448        String resourcePath;
13449
13450        /** New install */
13451        AsecInstallArgs(InstallParams params) {
13452            super(params.origin, params.move, params.observer, params.installFlags,
13453                    params.installerPackageName, params.volumeUuid,
13454                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13455                    params.grantedRuntimePermissions,
13456                    params.traceMethod, params.traceCookie, params.certificates);
13457        }
13458
13459        /** Existing install */
13460        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13461                        boolean isExternal, boolean isForwardLocked) {
13462            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13463              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13464                    instructionSets, null, null, null, 0, null /*certificates*/);
13465            // Hackily pretend we're still looking at a full code path
13466            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13467                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13468            }
13469
13470            // Extract cid from fullCodePath
13471            int eidx = fullCodePath.lastIndexOf("/");
13472            String subStr1 = fullCodePath.substring(0, eidx);
13473            int sidx = subStr1.lastIndexOf("/");
13474            cid = subStr1.substring(sidx+1, eidx);
13475            setMountPath(subStr1);
13476        }
13477
13478        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13479            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13480              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13481                    instructionSets, null, null, null, 0, null /*certificates*/);
13482            this.cid = cid;
13483            setMountPath(PackageHelper.getSdDir(cid));
13484        }
13485
13486        void createCopyFile() {
13487            cid = mInstallerService.allocateExternalStageCidLegacy();
13488        }
13489
13490        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13491            if (origin.staged && origin.cid != null) {
13492                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13493                cid = origin.cid;
13494                setMountPath(PackageHelper.getSdDir(cid));
13495                return PackageManager.INSTALL_SUCCEEDED;
13496            }
13497
13498            if (temp) {
13499                createCopyFile();
13500            } else {
13501                /*
13502                 * Pre-emptively destroy the container since it's destroyed if
13503                 * copying fails due to it existing anyway.
13504                 */
13505                PackageHelper.destroySdDir(cid);
13506            }
13507
13508            final String newMountPath = imcs.copyPackageToContainer(
13509                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13510                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13511
13512            if (newMountPath != null) {
13513                setMountPath(newMountPath);
13514                return PackageManager.INSTALL_SUCCEEDED;
13515            } else {
13516                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13517            }
13518        }
13519
13520        @Override
13521        String getCodePath() {
13522            return packagePath;
13523        }
13524
13525        @Override
13526        String getResourcePath() {
13527            return resourcePath;
13528        }
13529
13530        int doPreInstall(int status) {
13531            if (status != PackageManager.INSTALL_SUCCEEDED) {
13532                // Destroy container
13533                PackageHelper.destroySdDir(cid);
13534            } else {
13535                boolean mounted = PackageHelper.isContainerMounted(cid);
13536                if (!mounted) {
13537                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13538                            Process.SYSTEM_UID);
13539                    if (newMountPath != null) {
13540                        setMountPath(newMountPath);
13541                    } else {
13542                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13543                    }
13544                }
13545            }
13546            return status;
13547        }
13548
13549        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13550            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13551            String newMountPath = null;
13552            if (PackageHelper.isContainerMounted(cid)) {
13553                // Unmount the container
13554                if (!PackageHelper.unMountSdDir(cid)) {
13555                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13556                    return false;
13557                }
13558            }
13559            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13560                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13561                        " which might be stale. Will try to clean up.");
13562                // Clean up the stale container and proceed to recreate.
13563                if (!PackageHelper.destroySdDir(newCacheId)) {
13564                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13565                    return false;
13566                }
13567                // Successfully cleaned up stale container. Try to rename again.
13568                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13569                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13570                            + " inspite of cleaning it up.");
13571                    return false;
13572                }
13573            }
13574            if (!PackageHelper.isContainerMounted(newCacheId)) {
13575                Slog.w(TAG, "Mounting container " + newCacheId);
13576                newMountPath = PackageHelper.mountSdDir(newCacheId,
13577                        getEncryptKey(), Process.SYSTEM_UID);
13578            } else {
13579                newMountPath = PackageHelper.getSdDir(newCacheId);
13580            }
13581            if (newMountPath == null) {
13582                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13583                return false;
13584            }
13585            Log.i(TAG, "Succesfully renamed " + cid +
13586                    " to " + newCacheId +
13587                    " at new path: " + newMountPath);
13588            cid = newCacheId;
13589
13590            final File beforeCodeFile = new File(packagePath);
13591            setMountPath(newMountPath);
13592            final File afterCodeFile = new File(packagePath);
13593
13594            // Reflect the rename in scanned details
13595            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13596            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13597                    afterCodeFile, pkg.baseCodePath));
13598            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13599                    afterCodeFile, pkg.splitCodePaths));
13600
13601            // Reflect the rename in app info
13602            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13603            pkg.setApplicationInfoCodePath(pkg.codePath);
13604            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13605            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13606            pkg.setApplicationInfoResourcePath(pkg.codePath);
13607            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13608            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13609
13610            return true;
13611        }
13612
13613        private void setMountPath(String mountPath) {
13614            final File mountFile = new File(mountPath);
13615
13616            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13617            if (monolithicFile.exists()) {
13618                packagePath = monolithicFile.getAbsolutePath();
13619                if (isFwdLocked()) {
13620                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13621                } else {
13622                    resourcePath = packagePath;
13623                }
13624            } else {
13625                packagePath = mountFile.getAbsolutePath();
13626                resourcePath = packagePath;
13627            }
13628        }
13629
13630        int doPostInstall(int status, int uid) {
13631            if (status != PackageManager.INSTALL_SUCCEEDED) {
13632                cleanUp();
13633            } else {
13634                final int groupOwner;
13635                final String protectedFile;
13636                if (isFwdLocked()) {
13637                    groupOwner = UserHandle.getSharedAppGid(uid);
13638                    protectedFile = RES_FILE_NAME;
13639                } else {
13640                    groupOwner = -1;
13641                    protectedFile = null;
13642                }
13643
13644                if (uid < Process.FIRST_APPLICATION_UID
13645                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13646                    Slog.e(TAG, "Failed to finalize " + cid);
13647                    PackageHelper.destroySdDir(cid);
13648                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13649                }
13650
13651                boolean mounted = PackageHelper.isContainerMounted(cid);
13652                if (!mounted) {
13653                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13654                }
13655            }
13656            return status;
13657        }
13658
13659        private void cleanUp() {
13660            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13661
13662            // Destroy secure container
13663            PackageHelper.destroySdDir(cid);
13664        }
13665
13666        private List<String> getAllCodePaths() {
13667            final File codeFile = new File(getCodePath());
13668            if (codeFile != null && codeFile.exists()) {
13669                try {
13670                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13671                    return pkg.getAllCodePaths();
13672                } catch (PackageParserException e) {
13673                    // Ignored; we tried our best
13674                }
13675            }
13676            return Collections.EMPTY_LIST;
13677        }
13678
13679        void cleanUpResourcesLI() {
13680            // Enumerate all code paths before deleting
13681            cleanUpResourcesLI(getAllCodePaths());
13682        }
13683
13684        private void cleanUpResourcesLI(List<String> allCodePaths) {
13685            cleanUp();
13686            removeDexFiles(allCodePaths, instructionSets);
13687        }
13688
13689        String getPackageName() {
13690            return getAsecPackageName(cid);
13691        }
13692
13693        boolean doPostDeleteLI(boolean delete) {
13694            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13695            final List<String> allCodePaths = getAllCodePaths();
13696            boolean mounted = PackageHelper.isContainerMounted(cid);
13697            if (mounted) {
13698                // Unmount first
13699                if (PackageHelper.unMountSdDir(cid)) {
13700                    mounted = false;
13701                }
13702            }
13703            if (!mounted && delete) {
13704                cleanUpResourcesLI(allCodePaths);
13705            }
13706            return !mounted;
13707        }
13708
13709        @Override
13710        int doPreCopy() {
13711            if (isFwdLocked()) {
13712                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13713                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13714                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13715                }
13716            }
13717
13718            return PackageManager.INSTALL_SUCCEEDED;
13719        }
13720
13721        @Override
13722        int doPostCopy(int uid) {
13723            if (isFwdLocked()) {
13724                if (uid < Process.FIRST_APPLICATION_UID
13725                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13726                                RES_FILE_NAME)) {
13727                    Slog.e(TAG, "Failed to finalize " + cid);
13728                    PackageHelper.destroySdDir(cid);
13729                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13730                }
13731            }
13732
13733            return PackageManager.INSTALL_SUCCEEDED;
13734        }
13735    }
13736
13737    /**
13738     * Logic to handle movement of existing installed applications.
13739     */
13740    class MoveInstallArgs extends InstallArgs {
13741        private File codeFile;
13742        private File resourceFile;
13743
13744        /** New install */
13745        MoveInstallArgs(InstallParams params) {
13746            super(params.origin, params.move, params.observer, params.installFlags,
13747                    params.installerPackageName, params.volumeUuid,
13748                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13749                    params.grantedRuntimePermissions,
13750                    params.traceMethod, params.traceCookie, params.certificates);
13751        }
13752
13753        int copyApk(IMediaContainerService imcs, boolean temp) {
13754            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13755                    + move.fromUuid + " to " + move.toUuid);
13756            synchronized (mInstaller) {
13757                try {
13758                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13759                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13760                } catch (InstallerException e) {
13761                    Slog.w(TAG, "Failed to move app", e);
13762                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13763                }
13764            }
13765
13766            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13767            resourceFile = codeFile;
13768            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13769
13770            return PackageManager.INSTALL_SUCCEEDED;
13771        }
13772
13773        int doPreInstall(int status) {
13774            if (status != PackageManager.INSTALL_SUCCEEDED) {
13775                cleanUp(move.toUuid);
13776            }
13777            return status;
13778        }
13779
13780        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13781            if (status != PackageManager.INSTALL_SUCCEEDED) {
13782                cleanUp(move.toUuid);
13783                return false;
13784            }
13785
13786            // Reflect the move in app info
13787            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13788            pkg.setApplicationInfoCodePath(pkg.codePath);
13789            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13790            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13791            pkg.setApplicationInfoResourcePath(pkg.codePath);
13792            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13793            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13794
13795            return true;
13796        }
13797
13798        int doPostInstall(int status, int uid) {
13799            if (status == PackageManager.INSTALL_SUCCEEDED) {
13800                cleanUp(move.fromUuid);
13801            } else {
13802                cleanUp(move.toUuid);
13803            }
13804            return status;
13805        }
13806
13807        @Override
13808        String getCodePath() {
13809            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13810        }
13811
13812        @Override
13813        String getResourcePath() {
13814            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13815        }
13816
13817        private boolean cleanUp(String volumeUuid) {
13818            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13819                    move.dataAppName);
13820            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13821            final int[] userIds = sUserManager.getUserIds();
13822            synchronized (mInstallLock) {
13823                // Clean up both app data and code
13824                // All package moves are frozen until finished
13825                for (int userId : userIds) {
13826                    try {
13827                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13828                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13829                    } catch (InstallerException e) {
13830                        Slog.w(TAG, String.valueOf(e));
13831                    }
13832                }
13833                removeCodePathLI(codeFile);
13834            }
13835            return true;
13836        }
13837
13838        void cleanUpResourcesLI() {
13839            throw new UnsupportedOperationException();
13840        }
13841
13842        boolean doPostDeleteLI(boolean delete) {
13843            throw new UnsupportedOperationException();
13844        }
13845    }
13846
13847    static String getAsecPackageName(String packageCid) {
13848        int idx = packageCid.lastIndexOf("-");
13849        if (idx == -1) {
13850            return packageCid;
13851        }
13852        return packageCid.substring(0, idx);
13853    }
13854
13855    // Utility method used to create code paths based on package name and available index.
13856    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13857        String idxStr = "";
13858        int idx = 1;
13859        // Fall back to default value of idx=1 if prefix is not
13860        // part of oldCodePath
13861        if (oldCodePath != null) {
13862            String subStr = oldCodePath;
13863            // Drop the suffix right away
13864            if (suffix != null && subStr.endsWith(suffix)) {
13865                subStr = subStr.substring(0, subStr.length() - suffix.length());
13866            }
13867            // If oldCodePath already contains prefix find out the
13868            // ending index to either increment or decrement.
13869            int sidx = subStr.lastIndexOf(prefix);
13870            if (sidx != -1) {
13871                subStr = subStr.substring(sidx + prefix.length());
13872                if (subStr != null) {
13873                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13874                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13875                    }
13876                    try {
13877                        idx = Integer.parseInt(subStr);
13878                        if (idx <= 1) {
13879                            idx++;
13880                        } else {
13881                            idx--;
13882                        }
13883                    } catch(NumberFormatException e) {
13884                    }
13885                }
13886            }
13887        }
13888        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13889        return prefix + idxStr;
13890    }
13891
13892    private File getNextCodePath(File targetDir, String packageName) {
13893        int suffix = 1;
13894        File result;
13895        do {
13896            result = new File(targetDir, packageName + "-" + suffix);
13897            suffix++;
13898        } while (result.exists());
13899        return result;
13900    }
13901
13902    // Utility method that returns the relative package path with respect
13903    // to the installation directory. Like say for /data/data/com.test-1.apk
13904    // string com.test-1 is returned.
13905    static String deriveCodePathName(String codePath) {
13906        if (codePath == null) {
13907            return null;
13908        }
13909        final File codeFile = new File(codePath);
13910        final String name = codeFile.getName();
13911        if (codeFile.isDirectory()) {
13912            return name;
13913        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13914            final int lastDot = name.lastIndexOf('.');
13915            return name.substring(0, lastDot);
13916        } else {
13917            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13918            return null;
13919        }
13920    }
13921
13922    static class PackageInstalledInfo {
13923        String name;
13924        int uid;
13925        // The set of users that originally had this package installed.
13926        int[] origUsers;
13927        // The set of users that now have this package installed.
13928        int[] newUsers;
13929        PackageParser.Package pkg;
13930        int returnCode;
13931        String returnMsg;
13932        PackageRemovedInfo removedInfo;
13933        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13934
13935        public void setError(int code, String msg) {
13936            setReturnCode(code);
13937            setReturnMessage(msg);
13938            Slog.w(TAG, msg);
13939        }
13940
13941        public void setError(String msg, PackageParserException e) {
13942            setReturnCode(e.error);
13943            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13944            Slog.w(TAG, msg, e);
13945        }
13946
13947        public void setError(String msg, PackageManagerException e) {
13948            returnCode = e.error;
13949            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13950            Slog.w(TAG, msg, e);
13951        }
13952
13953        public void setReturnCode(int returnCode) {
13954            this.returnCode = returnCode;
13955            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13956            for (int i = 0; i < childCount; i++) {
13957                addedChildPackages.valueAt(i).returnCode = returnCode;
13958            }
13959        }
13960
13961        private void setReturnMessage(String returnMsg) {
13962            this.returnMsg = returnMsg;
13963            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13964            for (int i = 0; i < childCount; i++) {
13965                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13966            }
13967        }
13968
13969        // In some error cases we want to convey more info back to the observer
13970        String origPackage;
13971        String origPermission;
13972    }
13973
13974    /*
13975     * Install a non-existing package.
13976     */
13977    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
13978            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
13979            PackageInstalledInfo res) {
13980        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13981
13982        // Remember this for later, in case we need to rollback this install
13983        String pkgName = pkg.packageName;
13984
13985        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13986
13987        synchronized(mPackages) {
13988            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13989                // A package with the same name is already installed, though
13990                // it has been renamed to an older name.  The package we
13991                // are trying to install should be installed as an update to
13992                // the existing one, but that has not been requested, so bail.
13993                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13994                        + " without first uninstalling package running as "
13995                        + mSettings.mRenamedPackages.get(pkgName));
13996                return;
13997            }
13998            if (mPackages.containsKey(pkgName)) {
13999                // Don't allow installation over an existing package with the same name.
14000                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14001                        + " without first uninstalling.");
14002                return;
14003            }
14004        }
14005
14006        try {
14007            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14008                    System.currentTimeMillis(), user);
14009
14010            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14011
14012            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14013                prepareAppDataAfterInstallLIF(newPackage);
14014
14015            } else {
14016                // Remove package from internal structures, but keep around any
14017                // data that might have already existed
14018                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14019                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14020            }
14021        } catch (PackageManagerException e) {
14022            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14023        }
14024
14025        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14026    }
14027
14028    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14029        // Can't rotate keys during boot or if sharedUser.
14030        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14031                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14032            return false;
14033        }
14034        // app is using upgradeKeySets; make sure all are valid
14035        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14036        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14037        for (int i = 0; i < upgradeKeySets.length; i++) {
14038            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14039                Slog.wtf(TAG, "Package "
14040                         + (oldPs.name != null ? oldPs.name : "<null>")
14041                         + " contains upgrade-key-set reference to unknown key-set: "
14042                         + upgradeKeySets[i]
14043                         + " reverting to signatures check.");
14044                return false;
14045            }
14046        }
14047        return true;
14048    }
14049
14050    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14051        // Upgrade keysets are being used.  Determine if new package has a superset of the
14052        // required keys.
14053        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14054        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14055        for (int i = 0; i < upgradeKeySets.length; i++) {
14056            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14057            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14058                return true;
14059            }
14060        }
14061        return false;
14062    }
14063
14064    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14065        try (DigestInputStream digestStream =
14066                new DigestInputStream(new FileInputStream(file), digest)) {
14067            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14068        }
14069    }
14070
14071    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14072            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14073        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14074
14075        final PackageParser.Package oldPackage;
14076        final String pkgName = pkg.packageName;
14077        final int[] allUsers;
14078        final int[] installedUsers;
14079
14080        synchronized(mPackages) {
14081            oldPackage = mPackages.get(pkgName);
14082            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14083
14084            // don't allow upgrade to target a release SDK from a pre-release SDK
14085            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14086                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14087            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14088                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14089            if (oldTargetsPreRelease
14090                    && !newTargetsPreRelease
14091                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14092                Slog.w(TAG, "Can't install package targeting released sdk");
14093                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14094                return;
14095            }
14096
14097            // don't allow an upgrade from full to ephemeral
14098            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14099            if (isEphemeral && !oldIsEphemeral) {
14100                // can't downgrade from full to ephemeral
14101                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14102                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14103                return;
14104            }
14105
14106            // verify signatures are valid
14107            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14108            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14109                if (!checkUpgradeKeySetLP(ps, pkg)) {
14110                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14111                            "New package not signed by keys specified by upgrade-keysets: "
14112                                    + pkgName);
14113                    return;
14114                }
14115            } else {
14116                // default to original signature matching
14117                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14118                        != PackageManager.SIGNATURE_MATCH) {
14119                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14120                            "New package has a different signature: " + pkgName);
14121                    return;
14122                }
14123            }
14124
14125            // don't allow a system upgrade unless the upgrade hash matches
14126            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14127                byte[] digestBytes = null;
14128                try {
14129                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14130                    updateDigest(digest, new File(pkg.baseCodePath));
14131                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14132                        for (String path : pkg.splitCodePaths) {
14133                            updateDigest(digest, new File(path));
14134                        }
14135                    }
14136                    digestBytes = digest.digest();
14137                } catch (NoSuchAlgorithmException | IOException e) {
14138                    res.setError(INSTALL_FAILED_INVALID_APK,
14139                            "Could not compute hash: " + pkgName);
14140                    return;
14141                }
14142                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14143                    res.setError(INSTALL_FAILED_INVALID_APK,
14144                            "New package fails restrict-update check: " + pkgName);
14145                    return;
14146                }
14147                // retain upgrade restriction
14148                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14149            }
14150
14151            // Check for shared user id changes
14152            String invalidPackageName =
14153                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14154            if (invalidPackageName != null) {
14155                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14156                        "Package " + invalidPackageName + " tried to change user "
14157                                + oldPackage.mSharedUserId);
14158                return;
14159            }
14160
14161            // In case of rollback, remember per-user/profile install state
14162            allUsers = sUserManager.getUserIds();
14163            installedUsers = ps.queryInstalledUsers(allUsers, true);
14164        }
14165
14166        // Update what is removed
14167        res.removedInfo = new PackageRemovedInfo();
14168        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14169        res.removedInfo.removedPackage = oldPackage.packageName;
14170        res.removedInfo.isUpdate = true;
14171        res.removedInfo.origUsers = installedUsers;
14172        final int childCount = (oldPackage.childPackages != null)
14173                ? oldPackage.childPackages.size() : 0;
14174        for (int i = 0; i < childCount; i++) {
14175            boolean childPackageUpdated = false;
14176            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14177            if (res.addedChildPackages != null) {
14178                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14179                if (childRes != null) {
14180                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14181                    childRes.removedInfo.removedPackage = childPkg.packageName;
14182                    childRes.removedInfo.isUpdate = true;
14183                    childPackageUpdated = true;
14184                }
14185            }
14186            if (!childPackageUpdated) {
14187                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14188                childRemovedRes.removedPackage = childPkg.packageName;
14189                childRemovedRes.isUpdate = false;
14190                childRemovedRes.dataRemoved = true;
14191                synchronized (mPackages) {
14192                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14193                    if (childPs != null) {
14194                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14195                    }
14196                }
14197                if (res.removedInfo.removedChildPackages == null) {
14198                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14199                }
14200                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14201            }
14202        }
14203
14204        boolean sysPkg = (isSystemApp(oldPackage));
14205        if (sysPkg) {
14206            // Set the system/privileged flags as needed
14207            final boolean privileged =
14208                    (oldPackage.applicationInfo.privateFlags
14209                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14210            final int systemPolicyFlags = policyFlags
14211                    | PackageParser.PARSE_IS_SYSTEM
14212                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14213
14214            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14215                    user, allUsers, installerPackageName, res);
14216        } else {
14217            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14218                    user, allUsers, installerPackageName, res);
14219        }
14220    }
14221
14222    public List<String> getPreviousCodePaths(String packageName) {
14223        final PackageSetting ps = mSettings.mPackages.get(packageName);
14224        final List<String> result = new ArrayList<String>();
14225        if (ps != null && ps.oldCodePaths != null) {
14226            result.addAll(ps.oldCodePaths);
14227        }
14228        return result;
14229    }
14230
14231    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14232            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14233            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14234        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14235                + deletedPackage);
14236
14237        String pkgName = deletedPackage.packageName;
14238        boolean deletedPkg = true;
14239        boolean addedPkg = false;
14240        boolean updatedSettings = false;
14241        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14242        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14243                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14244
14245        final long origUpdateTime = (pkg.mExtras != null)
14246                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14247
14248        // First delete the existing package while retaining the data directory
14249        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14250                res.removedInfo, true, pkg)) {
14251            // If the existing package wasn't successfully deleted
14252            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14253            deletedPkg = false;
14254        } else {
14255            // Successfully deleted the old package; proceed with replace.
14256
14257            // If deleted package lived in a container, give users a chance to
14258            // relinquish resources before killing.
14259            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14260                if (DEBUG_INSTALL) {
14261                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14262                }
14263                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14264                final ArrayList<String> pkgList = new ArrayList<String>(1);
14265                pkgList.add(deletedPackage.applicationInfo.packageName);
14266                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14267            }
14268
14269            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14270                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14271            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14272
14273            try {
14274                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14275                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14276                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14277
14278                // Update the in-memory copy of the previous code paths.
14279                PackageSetting ps = mSettings.mPackages.get(pkgName);
14280                if (!killApp) {
14281                    if (ps.oldCodePaths == null) {
14282                        ps.oldCodePaths = new ArraySet<>();
14283                    }
14284                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14285                    if (deletedPackage.splitCodePaths != null) {
14286                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14287                    }
14288                } else {
14289                    ps.oldCodePaths = null;
14290                }
14291                if (ps.childPackageNames != null) {
14292                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14293                        final String childPkgName = ps.childPackageNames.get(i);
14294                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14295                        childPs.oldCodePaths = ps.oldCodePaths;
14296                    }
14297                }
14298                prepareAppDataAfterInstallLIF(newPackage);
14299                addedPkg = true;
14300            } catch (PackageManagerException e) {
14301                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14302            }
14303        }
14304
14305        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14306            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14307
14308            // Revert all internal state mutations and added folders for the failed install
14309            if (addedPkg) {
14310                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14311                        res.removedInfo, true, null);
14312            }
14313
14314            // Restore the old package
14315            if (deletedPkg) {
14316                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14317                File restoreFile = new File(deletedPackage.codePath);
14318                // Parse old package
14319                boolean oldExternal = isExternal(deletedPackage);
14320                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14321                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14322                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14323                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14324                try {
14325                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14326                            null);
14327                } catch (PackageManagerException e) {
14328                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14329                            + e.getMessage());
14330                    return;
14331                }
14332
14333                synchronized (mPackages) {
14334                    // Ensure the installer package name up to date
14335                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14336
14337                    // Update permissions for restored package
14338                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14339
14340                    mSettings.writeLPr();
14341                }
14342
14343                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14344            }
14345        } else {
14346            synchronized (mPackages) {
14347                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14348                if (ps != null) {
14349                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14350                    if (res.removedInfo.removedChildPackages != null) {
14351                        final int childCount = res.removedInfo.removedChildPackages.size();
14352                        // Iterate in reverse as we may modify the collection
14353                        for (int i = childCount - 1; i >= 0; i--) {
14354                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14355                            if (res.addedChildPackages.containsKey(childPackageName)) {
14356                                res.removedInfo.removedChildPackages.removeAt(i);
14357                            } else {
14358                                PackageRemovedInfo childInfo = res.removedInfo
14359                                        .removedChildPackages.valueAt(i);
14360                                childInfo.removedForAllUsers = mPackages.get(
14361                                        childInfo.removedPackage) == null;
14362                            }
14363                        }
14364                    }
14365                }
14366            }
14367        }
14368    }
14369
14370    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14371            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14372            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14373        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14374                + ", old=" + deletedPackage);
14375
14376        final boolean disabledSystem;
14377
14378        // Remove existing system package
14379        removePackageLI(deletedPackage, true);
14380
14381        synchronized (mPackages) {
14382            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14383        }
14384        if (!disabledSystem) {
14385            // We didn't need to disable the .apk as a current system package,
14386            // which means we are replacing another update that is already
14387            // installed.  We need to make sure to delete the older one's .apk.
14388            res.removedInfo.args = createInstallArgsForExisting(0,
14389                    deletedPackage.applicationInfo.getCodePath(),
14390                    deletedPackage.applicationInfo.getResourcePath(),
14391                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14392        } else {
14393            res.removedInfo.args = null;
14394        }
14395
14396        // Successfully disabled the old package. Now proceed with re-installation
14397        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14398                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14399        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14400
14401        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14402        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14403                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14404
14405        PackageParser.Package newPackage = null;
14406        try {
14407            // Add the package to the internal data structures
14408            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14409
14410            // Set the update and install times
14411            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14412            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14413                    System.currentTimeMillis());
14414
14415            // Update the package dynamic state if succeeded
14416            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14417                // Now that the install succeeded make sure we remove data
14418                // directories for any child package the update removed.
14419                final int deletedChildCount = (deletedPackage.childPackages != null)
14420                        ? deletedPackage.childPackages.size() : 0;
14421                final int newChildCount = (newPackage.childPackages != null)
14422                        ? newPackage.childPackages.size() : 0;
14423                for (int i = 0; i < deletedChildCount; i++) {
14424                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14425                    boolean childPackageDeleted = true;
14426                    for (int j = 0; j < newChildCount; j++) {
14427                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14428                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14429                            childPackageDeleted = false;
14430                            break;
14431                        }
14432                    }
14433                    if (childPackageDeleted) {
14434                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14435                                deletedChildPkg.packageName);
14436                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14437                            PackageRemovedInfo removedChildRes = res.removedInfo
14438                                    .removedChildPackages.get(deletedChildPkg.packageName);
14439                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14440                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14441                        }
14442                    }
14443                }
14444
14445                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14446                prepareAppDataAfterInstallLIF(newPackage);
14447            }
14448        } catch (PackageManagerException e) {
14449            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14450            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14451        }
14452
14453        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14454            // Re installation failed. Restore old information
14455            // Remove new pkg information
14456            if (newPackage != null) {
14457                removeInstalledPackageLI(newPackage, true);
14458            }
14459            // Add back the old system package
14460            try {
14461                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14462            } catch (PackageManagerException e) {
14463                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14464            }
14465
14466            synchronized (mPackages) {
14467                if (disabledSystem) {
14468                    enableSystemPackageLPw(deletedPackage);
14469                }
14470
14471                // Ensure the installer package name up to date
14472                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14473
14474                // Update permissions for restored package
14475                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14476
14477                mSettings.writeLPr();
14478            }
14479
14480            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14481                    + " after failed upgrade");
14482        }
14483    }
14484
14485    /**
14486     * Checks whether the parent or any of the child packages have a change shared
14487     * user. For a package to be a valid update the shred users of the parent and
14488     * the children should match. We may later support changing child shared users.
14489     * @param oldPkg The updated package.
14490     * @param newPkg The update package.
14491     * @return The shared user that change between the versions.
14492     */
14493    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14494            PackageParser.Package newPkg) {
14495        // Check parent shared user
14496        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14497            return newPkg.packageName;
14498        }
14499        // Check child shared users
14500        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14501        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14502        for (int i = 0; i < newChildCount; i++) {
14503            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14504            // If this child was present, did it have the same shared user?
14505            for (int j = 0; j < oldChildCount; j++) {
14506                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14507                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14508                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14509                    return newChildPkg.packageName;
14510                }
14511            }
14512        }
14513        return null;
14514    }
14515
14516    private void removeNativeBinariesLI(PackageSetting ps) {
14517        // Remove the lib path for the parent package
14518        if (ps != null) {
14519            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14520            // Remove the lib path for the child packages
14521            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14522            for (int i = 0; i < childCount; i++) {
14523                PackageSetting childPs = null;
14524                synchronized (mPackages) {
14525                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14526                }
14527                if (childPs != null) {
14528                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14529                            .legacyNativeLibraryPathString);
14530                }
14531            }
14532        }
14533    }
14534
14535    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14536        // Enable the parent package
14537        mSettings.enableSystemPackageLPw(pkg.packageName);
14538        // Enable the child packages
14539        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14540        for (int i = 0; i < childCount; i++) {
14541            PackageParser.Package childPkg = pkg.childPackages.get(i);
14542            mSettings.enableSystemPackageLPw(childPkg.packageName);
14543        }
14544    }
14545
14546    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14547            PackageParser.Package newPkg) {
14548        // Disable the parent package (parent always replaced)
14549        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14550        // Disable the child packages
14551        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14552        for (int i = 0; i < childCount; i++) {
14553            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14554            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14555            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14556        }
14557        return disabled;
14558    }
14559
14560    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14561            String installerPackageName) {
14562        // Enable the parent package
14563        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14564        // Enable the child packages
14565        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14566        for (int i = 0; i < childCount; i++) {
14567            PackageParser.Package childPkg = pkg.childPackages.get(i);
14568            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14569        }
14570    }
14571
14572    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14573        // Collect all used permissions in the UID
14574        ArraySet<String> usedPermissions = new ArraySet<>();
14575        final int packageCount = su.packages.size();
14576        for (int i = 0; i < packageCount; i++) {
14577            PackageSetting ps = su.packages.valueAt(i);
14578            if (ps.pkg == null) {
14579                continue;
14580            }
14581            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14582            for (int j = 0; j < requestedPermCount; j++) {
14583                String permission = ps.pkg.requestedPermissions.get(j);
14584                BasePermission bp = mSettings.mPermissions.get(permission);
14585                if (bp != null) {
14586                    usedPermissions.add(permission);
14587                }
14588            }
14589        }
14590
14591        PermissionsState permissionsState = su.getPermissionsState();
14592        // Prune install permissions
14593        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14594        final int installPermCount = installPermStates.size();
14595        for (int i = installPermCount - 1; i >= 0;  i--) {
14596            PermissionState permissionState = installPermStates.get(i);
14597            if (!usedPermissions.contains(permissionState.getName())) {
14598                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14599                if (bp != null) {
14600                    permissionsState.revokeInstallPermission(bp);
14601                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14602                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14603                }
14604            }
14605        }
14606
14607        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14608
14609        // Prune runtime permissions
14610        for (int userId : allUserIds) {
14611            List<PermissionState> runtimePermStates = permissionsState
14612                    .getRuntimePermissionStates(userId);
14613            final int runtimePermCount = runtimePermStates.size();
14614            for (int i = runtimePermCount - 1; i >= 0; i--) {
14615                PermissionState permissionState = runtimePermStates.get(i);
14616                if (!usedPermissions.contains(permissionState.getName())) {
14617                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14618                    if (bp != null) {
14619                        permissionsState.revokeRuntimePermission(bp, userId);
14620                        permissionsState.updatePermissionFlags(bp, userId,
14621                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14622                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14623                                runtimePermissionChangedUserIds, userId);
14624                    }
14625                }
14626            }
14627        }
14628
14629        return runtimePermissionChangedUserIds;
14630    }
14631
14632    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14633            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14634        // Update the parent package setting
14635        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14636                res, user);
14637        // Update the child packages setting
14638        final int childCount = (newPackage.childPackages != null)
14639                ? newPackage.childPackages.size() : 0;
14640        for (int i = 0; i < childCount; i++) {
14641            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14642            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14643            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14644                    childRes.origUsers, childRes, user);
14645        }
14646    }
14647
14648    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14649            String installerPackageName, int[] allUsers, int[] installedForUsers,
14650            PackageInstalledInfo res, UserHandle user) {
14651        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14652
14653        String pkgName = newPackage.packageName;
14654        synchronized (mPackages) {
14655            //write settings. the installStatus will be incomplete at this stage.
14656            //note that the new package setting would have already been
14657            //added to mPackages. It hasn't been persisted yet.
14658            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14659            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14660            mSettings.writeLPr();
14661            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14662        }
14663
14664        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14665        synchronized (mPackages) {
14666            updatePermissionsLPw(newPackage.packageName, newPackage,
14667                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14668                            ? UPDATE_PERMISSIONS_ALL : 0));
14669            // For system-bundled packages, we assume that installing an upgraded version
14670            // of the package implies that the user actually wants to run that new code,
14671            // so we enable the package.
14672            PackageSetting ps = mSettings.mPackages.get(pkgName);
14673            final int userId = user.getIdentifier();
14674            if (ps != null) {
14675                if (isSystemApp(newPackage)) {
14676                    if (DEBUG_INSTALL) {
14677                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14678                    }
14679                    // Enable system package for requested users
14680                    if (res.origUsers != null) {
14681                        for (int origUserId : res.origUsers) {
14682                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14683                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14684                                        origUserId, installerPackageName);
14685                            }
14686                        }
14687                    }
14688                    // Also convey the prior install/uninstall state
14689                    if (allUsers != null && installedForUsers != null) {
14690                        for (int currentUserId : allUsers) {
14691                            final boolean installed = ArrayUtils.contains(
14692                                    installedForUsers, currentUserId);
14693                            if (DEBUG_INSTALL) {
14694                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14695                            }
14696                            ps.setInstalled(installed, currentUserId);
14697                        }
14698                        // these install state changes will be persisted in the
14699                        // upcoming call to mSettings.writeLPr().
14700                    }
14701                }
14702                // It's implied that when a user requests installation, they want the app to be
14703                // installed and enabled.
14704                if (userId != UserHandle.USER_ALL) {
14705                    ps.setInstalled(true, userId);
14706                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14707                }
14708            }
14709            res.name = pkgName;
14710            res.uid = newPackage.applicationInfo.uid;
14711            res.pkg = newPackage;
14712            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14713            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14714            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14715            //to update install status
14716            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14717            mSettings.writeLPr();
14718            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14719        }
14720
14721        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14722    }
14723
14724    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14725        try {
14726            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14727            installPackageLI(args, res);
14728        } finally {
14729            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14730        }
14731    }
14732
14733    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14734        final int installFlags = args.installFlags;
14735        final String installerPackageName = args.installerPackageName;
14736        final String volumeUuid = args.volumeUuid;
14737        final File tmpPackageFile = new File(args.getCodePath());
14738        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14739        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14740                || (args.volumeUuid != null));
14741        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14742        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14743        boolean replace = false;
14744        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14745        if (args.move != null) {
14746            // moving a complete application; perform an initial scan on the new install location
14747            scanFlags |= SCAN_INITIAL;
14748        }
14749        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14750            scanFlags |= SCAN_DONT_KILL_APP;
14751        }
14752
14753        // Result object to be returned
14754        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14755
14756        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14757
14758        // Sanity check
14759        if (ephemeral && (forwardLocked || onExternal)) {
14760            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14761                    + " external=" + onExternal);
14762            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14763            return;
14764        }
14765
14766        // Retrieve PackageSettings and parse package
14767        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14768                | PackageParser.PARSE_ENFORCE_CODE
14769                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14770                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14771                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14772                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14773        PackageParser pp = new PackageParser();
14774        pp.setSeparateProcesses(mSeparateProcesses);
14775        pp.setDisplayMetrics(mMetrics);
14776
14777        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14778        final PackageParser.Package pkg;
14779        try {
14780            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14781        } catch (PackageParserException e) {
14782            res.setError("Failed parse during installPackageLI", e);
14783            return;
14784        } finally {
14785            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14786        }
14787
14788        // If we are installing a clustered package add results for the children
14789        if (pkg.childPackages != null) {
14790            synchronized (mPackages) {
14791                final int childCount = pkg.childPackages.size();
14792                for (int i = 0; i < childCount; i++) {
14793                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14794                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14795                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14796                    childRes.pkg = childPkg;
14797                    childRes.name = childPkg.packageName;
14798                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14799                    if (childPs != null) {
14800                        childRes.origUsers = childPs.queryInstalledUsers(
14801                                sUserManager.getUserIds(), true);
14802                    }
14803                    if ((mPackages.containsKey(childPkg.packageName))) {
14804                        childRes.removedInfo = new PackageRemovedInfo();
14805                        childRes.removedInfo.removedPackage = childPkg.packageName;
14806                    }
14807                    if (res.addedChildPackages == null) {
14808                        res.addedChildPackages = new ArrayMap<>();
14809                    }
14810                    res.addedChildPackages.put(childPkg.packageName, childRes);
14811                }
14812            }
14813        }
14814
14815        // If package doesn't declare API override, mark that we have an install
14816        // time CPU ABI override.
14817        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14818            pkg.cpuAbiOverride = args.abiOverride;
14819        }
14820
14821        String pkgName = res.name = pkg.packageName;
14822        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14823            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14824                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14825                return;
14826            }
14827        }
14828
14829        try {
14830            // either use what we've been given or parse directly from the APK
14831            if (args.certificates != null) {
14832                try {
14833                    PackageParser.populateCertificates(pkg, args.certificates);
14834                } catch (PackageParserException e) {
14835                    // there was something wrong with the certificates we were given;
14836                    // try to pull them from the APK
14837                    PackageParser.collectCertificates(pkg, parseFlags);
14838                }
14839            } else {
14840                PackageParser.collectCertificates(pkg, parseFlags);
14841            }
14842        } catch (PackageParserException e) {
14843            res.setError("Failed collect during installPackageLI", e);
14844            return;
14845        }
14846
14847        // Get rid of all references to package scan path via parser.
14848        pp = null;
14849        String oldCodePath = null;
14850        boolean systemApp = false;
14851        synchronized (mPackages) {
14852            // Check if installing already existing package
14853            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14854                String oldName = mSettings.mRenamedPackages.get(pkgName);
14855                if (pkg.mOriginalPackages != null
14856                        && pkg.mOriginalPackages.contains(oldName)
14857                        && mPackages.containsKey(oldName)) {
14858                    // This package is derived from an original package,
14859                    // and this device has been updating from that original
14860                    // name.  We must continue using the original name, so
14861                    // rename the new package here.
14862                    pkg.setPackageName(oldName);
14863                    pkgName = pkg.packageName;
14864                    replace = true;
14865                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14866                            + oldName + " pkgName=" + pkgName);
14867                } else if (mPackages.containsKey(pkgName)) {
14868                    // This package, under its official name, already exists
14869                    // on the device; we should replace it.
14870                    replace = true;
14871                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14872                }
14873
14874                // Child packages are installed through the parent package
14875                if (pkg.parentPackage != null) {
14876                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14877                            "Package " + pkg.packageName + " is child of package "
14878                                    + pkg.parentPackage.parentPackage + ". Child packages "
14879                                    + "can be updated only through the parent package.");
14880                    return;
14881                }
14882
14883                if (replace) {
14884                    // Prevent apps opting out from runtime permissions
14885                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14886                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14887                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14888                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14889                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14890                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14891                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14892                                        + " doesn't support runtime permissions but the old"
14893                                        + " target SDK " + oldTargetSdk + " does.");
14894                        return;
14895                    }
14896
14897                    // Prevent installing of child packages
14898                    if (oldPackage.parentPackage != null) {
14899                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14900                                "Package " + pkg.packageName + " is child of package "
14901                                        + oldPackage.parentPackage + ". Child packages "
14902                                        + "can be updated only through the parent package.");
14903                        return;
14904                    }
14905                }
14906            }
14907
14908            PackageSetting ps = mSettings.mPackages.get(pkgName);
14909            if (ps != null) {
14910                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14911
14912                // Quick sanity check that we're signed correctly if updating;
14913                // we'll check this again later when scanning, but we want to
14914                // bail early here before tripping over redefined permissions.
14915                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14916                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14917                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14918                                + pkg.packageName + " upgrade keys do not match the "
14919                                + "previously installed version");
14920                        return;
14921                    }
14922                } else {
14923                    try {
14924                        verifySignaturesLP(ps, pkg);
14925                    } catch (PackageManagerException e) {
14926                        res.setError(e.error, e.getMessage());
14927                        return;
14928                    }
14929                }
14930
14931                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14932                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14933                    systemApp = (ps.pkg.applicationInfo.flags &
14934                            ApplicationInfo.FLAG_SYSTEM) != 0;
14935                }
14936                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14937            }
14938
14939            // Check whether the newly-scanned package wants to define an already-defined perm
14940            int N = pkg.permissions.size();
14941            for (int i = N-1; i >= 0; i--) {
14942                PackageParser.Permission perm = pkg.permissions.get(i);
14943                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14944                if (bp != null) {
14945                    // If the defining package is signed with our cert, it's okay.  This
14946                    // also includes the "updating the same package" case, of course.
14947                    // "updating same package" could also involve key-rotation.
14948                    final boolean sigsOk;
14949                    if (bp.sourcePackage.equals(pkg.packageName)
14950                            && (bp.packageSetting instanceof PackageSetting)
14951                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14952                                    scanFlags))) {
14953                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14954                    } else {
14955                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14956                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14957                    }
14958                    if (!sigsOk) {
14959                        // If the owning package is the system itself, we log but allow
14960                        // install to proceed; we fail the install on all other permission
14961                        // redefinitions.
14962                        if (!bp.sourcePackage.equals("android")) {
14963                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14964                                    + pkg.packageName + " attempting to redeclare permission "
14965                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14966                            res.origPermission = perm.info.name;
14967                            res.origPackage = bp.sourcePackage;
14968                            return;
14969                        } else {
14970                            Slog.w(TAG, "Package " + pkg.packageName
14971                                    + " attempting to redeclare system permission "
14972                                    + perm.info.name + "; ignoring new declaration");
14973                            pkg.permissions.remove(i);
14974                        }
14975                    }
14976                }
14977            }
14978        }
14979
14980        if (systemApp) {
14981            if (onExternal) {
14982                // Abort update; system app can't be replaced with app on sdcard
14983                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14984                        "Cannot install updates to system apps on sdcard");
14985                return;
14986            } else if (ephemeral) {
14987                // Abort update; system app can't be replaced with an ephemeral app
14988                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14989                        "Cannot update a system app with an ephemeral app");
14990                return;
14991            }
14992        }
14993
14994        if (args.move != null) {
14995            // We did an in-place move, so dex is ready to roll
14996            scanFlags |= SCAN_NO_DEX;
14997            scanFlags |= SCAN_MOVE;
14998
14999            synchronized (mPackages) {
15000                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15001                if (ps == null) {
15002                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15003                            "Missing settings for moved package " + pkgName);
15004                }
15005
15006                // We moved the entire application as-is, so bring over the
15007                // previously derived ABI information.
15008                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15009                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15010            }
15011
15012        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15013            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15014            scanFlags |= SCAN_NO_DEX;
15015
15016            try {
15017                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15018                    args.abiOverride : pkg.cpuAbiOverride);
15019                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15020                        true /* extract libs */);
15021            } catch (PackageManagerException pme) {
15022                Slog.e(TAG, "Error deriving application ABI", pme);
15023                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15024                return;
15025            }
15026
15027            // Shared libraries for the package need to be updated.
15028            synchronized (mPackages) {
15029                try {
15030                    updateSharedLibrariesLPw(pkg, null);
15031                } catch (PackageManagerException e) {
15032                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15033                }
15034            }
15035            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15036            // Do not run PackageDexOptimizer through the local performDexOpt
15037            // method because `pkg` may not be in `mPackages` yet.
15038            //
15039            // Also, don't fail application installs if the dexopt step fails.
15040            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15041                    null /* instructionSets */, false /* checkProfiles */,
15042                    getCompilerFilterForReason(REASON_INSTALL),
15043                    getOrCreateCompilerPackageStats(pkg));
15044            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15045
15046            // Notify BackgroundDexOptService that the package has been changed.
15047            // If this is an update of a package which used to fail to compile,
15048            // BDOS will remove it from its blacklist.
15049            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15050        }
15051
15052        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15053            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15054            return;
15055        }
15056
15057        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15058
15059        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15060                "installPackageLI")) {
15061            if (replace) {
15062                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15063                        installerPackageName, res);
15064            } else {
15065                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15066                        args.user, installerPackageName, volumeUuid, res);
15067            }
15068        }
15069        synchronized (mPackages) {
15070            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15071            if (ps != null) {
15072                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15073            }
15074
15075            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15076            for (int i = 0; i < childCount; i++) {
15077                PackageParser.Package childPkg = pkg.childPackages.get(i);
15078                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15079                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15080                if (childPs != null) {
15081                    childRes.newUsers = childPs.queryInstalledUsers(
15082                            sUserManager.getUserIds(), true);
15083                }
15084            }
15085        }
15086    }
15087
15088    private void startIntentFilterVerifications(int userId, boolean replacing,
15089            PackageParser.Package pkg) {
15090        if (mIntentFilterVerifierComponent == null) {
15091            Slog.w(TAG, "No IntentFilter verification will not be done as "
15092                    + "there is no IntentFilterVerifier available!");
15093            return;
15094        }
15095
15096        final int verifierUid = getPackageUid(
15097                mIntentFilterVerifierComponent.getPackageName(),
15098                MATCH_DEBUG_TRIAGED_MISSING,
15099                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15100
15101        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15102        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15103        mHandler.sendMessage(msg);
15104
15105        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15106        for (int i = 0; i < childCount; i++) {
15107            PackageParser.Package childPkg = pkg.childPackages.get(i);
15108            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15109            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15110            mHandler.sendMessage(msg);
15111        }
15112    }
15113
15114    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15115            PackageParser.Package pkg) {
15116        int size = pkg.activities.size();
15117        if (size == 0) {
15118            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15119                    "No activity, so no need to verify any IntentFilter!");
15120            return;
15121        }
15122
15123        final boolean hasDomainURLs = hasDomainURLs(pkg);
15124        if (!hasDomainURLs) {
15125            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15126                    "No domain URLs, so no need to verify any IntentFilter!");
15127            return;
15128        }
15129
15130        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15131                + " if any IntentFilter from the " + size
15132                + " Activities needs verification ...");
15133
15134        int count = 0;
15135        final String packageName = pkg.packageName;
15136
15137        synchronized (mPackages) {
15138            // If this is a new install and we see that we've already run verification for this
15139            // package, we have nothing to do: it means the state was restored from backup.
15140            if (!replacing) {
15141                IntentFilterVerificationInfo ivi =
15142                        mSettings.getIntentFilterVerificationLPr(packageName);
15143                if (ivi != null) {
15144                    if (DEBUG_DOMAIN_VERIFICATION) {
15145                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15146                                + ivi.getStatusString());
15147                    }
15148                    return;
15149                }
15150            }
15151
15152            // If any filters need to be verified, then all need to be.
15153            boolean needToVerify = false;
15154            for (PackageParser.Activity a : pkg.activities) {
15155                for (ActivityIntentInfo filter : a.intents) {
15156                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15157                        if (DEBUG_DOMAIN_VERIFICATION) {
15158                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15159                        }
15160                        needToVerify = true;
15161                        break;
15162                    }
15163                }
15164            }
15165
15166            if (needToVerify) {
15167                final int verificationId = mIntentFilterVerificationToken++;
15168                for (PackageParser.Activity a : pkg.activities) {
15169                    for (ActivityIntentInfo filter : a.intents) {
15170                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15171                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15172                                    "Verification needed for IntentFilter:" + filter.toString());
15173                            mIntentFilterVerifier.addOneIntentFilterVerification(
15174                                    verifierUid, userId, verificationId, filter, packageName);
15175                            count++;
15176                        }
15177                    }
15178                }
15179            }
15180        }
15181
15182        if (count > 0) {
15183            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15184                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15185                    +  " for userId:" + userId);
15186            mIntentFilterVerifier.startVerifications(userId);
15187        } else {
15188            if (DEBUG_DOMAIN_VERIFICATION) {
15189                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15190            }
15191        }
15192    }
15193
15194    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15195        final ComponentName cn  = filter.activity.getComponentName();
15196        final String packageName = cn.getPackageName();
15197
15198        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15199                packageName);
15200        if (ivi == null) {
15201            return true;
15202        }
15203        int status = ivi.getStatus();
15204        switch (status) {
15205            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15206            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15207                return true;
15208
15209            default:
15210                // Nothing to do
15211                return false;
15212        }
15213    }
15214
15215    private static boolean isMultiArch(ApplicationInfo info) {
15216        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15217    }
15218
15219    private static boolean isExternal(PackageParser.Package pkg) {
15220        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15221    }
15222
15223    private static boolean isExternal(PackageSetting ps) {
15224        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15225    }
15226
15227    private static boolean isEphemeral(PackageParser.Package pkg) {
15228        return pkg.applicationInfo.isEphemeralApp();
15229    }
15230
15231    private static boolean isEphemeral(PackageSetting ps) {
15232        return ps.pkg != null && isEphemeral(ps.pkg);
15233    }
15234
15235    private static boolean isSystemApp(PackageParser.Package pkg) {
15236        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15237    }
15238
15239    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15240        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15241    }
15242
15243    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15244        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15245    }
15246
15247    private static boolean isSystemApp(PackageSetting ps) {
15248        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15249    }
15250
15251    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15252        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15253    }
15254
15255    private int packageFlagsToInstallFlags(PackageSetting ps) {
15256        int installFlags = 0;
15257        if (isEphemeral(ps)) {
15258            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15259        }
15260        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15261            // This existing package was an external ASEC install when we have
15262            // the external flag without a UUID
15263            installFlags |= PackageManager.INSTALL_EXTERNAL;
15264        }
15265        if (ps.isForwardLocked()) {
15266            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15267        }
15268        return installFlags;
15269    }
15270
15271    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15272        if (isExternal(pkg)) {
15273            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15274                return StorageManager.UUID_PRIMARY_PHYSICAL;
15275            } else {
15276                return pkg.volumeUuid;
15277            }
15278        } else {
15279            return StorageManager.UUID_PRIVATE_INTERNAL;
15280        }
15281    }
15282
15283    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15284        if (isExternal(pkg)) {
15285            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15286                return mSettings.getExternalVersion();
15287            } else {
15288                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15289            }
15290        } else {
15291            return mSettings.getInternalVersion();
15292        }
15293    }
15294
15295    private void deleteTempPackageFiles() {
15296        final FilenameFilter filter = new FilenameFilter() {
15297            public boolean accept(File dir, String name) {
15298                return name.startsWith("vmdl") && name.endsWith(".tmp");
15299            }
15300        };
15301        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15302            file.delete();
15303        }
15304    }
15305
15306    @Override
15307    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15308            int flags) {
15309        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15310                flags);
15311    }
15312
15313    @Override
15314    public void deletePackage(final String packageName,
15315            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15316        mContext.enforceCallingOrSelfPermission(
15317                android.Manifest.permission.DELETE_PACKAGES, null);
15318        Preconditions.checkNotNull(packageName);
15319        Preconditions.checkNotNull(observer);
15320        final int uid = Binder.getCallingUid();
15321        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15322        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15323        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15324            mContext.enforceCallingOrSelfPermission(
15325                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15326                    "deletePackage for user " + userId);
15327        }
15328
15329        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15330            try {
15331                observer.onPackageDeleted(packageName,
15332                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15333            } catch (RemoteException re) {
15334            }
15335            return;
15336        }
15337
15338        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15339            try {
15340                observer.onPackageDeleted(packageName,
15341                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15342            } catch (RemoteException re) {
15343            }
15344            return;
15345        }
15346
15347        if (DEBUG_REMOVE) {
15348            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15349                    + " deleteAllUsers: " + deleteAllUsers );
15350        }
15351        // Queue up an async operation since the package deletion may take a little while.
15352        mHandler.post(new Runnable() {
15353            public void run() {
15354                mHandler.removeCallbacks(this);
15355                int returnCode;
15356                if (!deleteAllUsers) {
15357                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15358                } else {
15359                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15360                    // If nobody is blocking uninstall, proceed with delete for all users
15361                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15362                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15363                    } else {
15364                        // Otherwise uninstall individually for users with blockUninstalls=false
15365                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15366                        for (int userId : users) {
15367                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15368                                returnCode = deletePackageX(packageName, userId, userFlags);
15369                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15370                                    Slog.w(TAG, "Package delete failed for user " + userId
15371                                            + ", returnCode " + returnCode);
15372                                }
15373                            }
15374                        }
15375                        // The app has only been marked uninstalled for certain users.
15376                        // We still need to report that delete was blocked
15377                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15378                    }
15379                }
15380                try {
15381                    observer.onPackageDeleted(packageName, returnCode, null);
15382                } catch (RemoteException e) {
15383                    Log.i(TAG, "Observer no longer exists.");
15384                } //end catch
15385            } //end run
15386        });
15387    }
15388
15389    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15390        int[] result = EMPTY_INT_ARRAY;
15391        for (int userId : userIds) {
15392            if (getBlockUninstallForUser(packageName, userId)) {
15393                result = ArrayUtils.appendInt(result, userId);
15394            }
15395        }
15396        return result;
15397    }
15398
15399    @Override
15400    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15401        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15402    }
15403
15404    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15405        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15406                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15407        try {
15408            if (dpm != null) {
15409                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15410                        /* callingUserOnly =*/ false);
15411                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15412                        : deviceOwnerComponentName.getPackageName();
15413                // Does the package contains the device owner?
15414                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15415                // this check is probably not needed, since DO should be registered as a device
15416                // admin on some user too. (Original bug for this: b/17657954)
15417                if (packageName.equals(deviceOwnerPackageName)) {
15418                    return true;
15419                }
15420                // Does it contain a device admin for any user?
15421                int[] users;
15422                if (userId == UserHandle.USER_ALL) {
15423                    users = sUserManager.getUserIds();
15424                } else {
15425                    users = new int[]{userId};
15426                }
15427                for (int i = 0; i < users.length; ++i) {
15428                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15429                        return true;
15430                    }
15431                }
15432            }
15433        } catch (RemoteException e) {
15434        }
15435        return false;
15436    }
15437
15438    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15439        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15440    }
15441
15442    /**
15443     *  This method is an internal method that could be get invoked either
15444     *  to delete an installed package or to clean up a failed installation.
15445     *  After deleting an installed package, a broadcast is sent to notify any
15446     *  listeners that the package has been removed. For cleaning up a failed
15447     *  installation, the broadcast is not necessary since the package's
15448     *  installation wouldn't have sent the initial broadcast either
15449     *  The key steps in deleting a package are
15450     *  deleting the package information in internal structures like mPackages,
15451     *  deleting the packages base directories through installd
15452     *  updating mSettings to reflect current status
15453     *  persisting settings for later use
15454     *  sending a broadcast if necessary
15455     */
15456    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15457        final PackageRemovedInfo info = new PackageRemovedInfo();
15458        final boolean res;
15459
15460        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15461                ? UserHandle.USER_ALL : userId;
15462
15463        if (isPackageDeviceAdmin(packageName, removeUser)) {
15464            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15465            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15466        }
15467
15468        PackageSetting uninstalledPs = null;
15469
15470        // for the uninstall-updates case and restricted profiles, remember the per-
15471        // user handle installed state
15472        int[] allUsers;
15473        synchronized (mPackages) {
15474            uninstalledPs = mSettings.mPackages.get(packageName);
15475            if (uninstalledPs == null) {
15476                Slog.w(TAG, "Not removing non-existent package " + packageName);
15477                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15478            }
15479            allUsers = sUserManager.getUserIds();
15480            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15481        }
15482
15483        final int freezeUser;
15484        if (isUpdatedSystemApp(uninstalledPs)
15485                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15486            // We're downgrading a system app, which will apply to all users, so
15487            // freeze them all during the downgrade
15488            freezeUser = UserHandle.USER_ALL;
15489        } else {
15490            freezeUser = removeUser;
15491        }
15492
15493        synchronized (mInstallLock) {
15494            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15495            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15496                    deleteFlags, "deletePackageX")) {
15497                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15498                        deleteFlags | REMOVE_CHATTY, info, true, null);
15499            }
15500            synchronized (mPackages) {
15501                if (res) {
15502                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15503                }
15504            }
15505        }
15506
15507        if (res) {
15508            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15509            info.sendPackageRemovedBroadcasts(killApp);
15510            info.sendSystemPackageUpdatedBroadcasts();
15511            info.sendSystemPackageAppearedBroadcasts();
15512        }
15513        // Force a gc here.
15514        Runtime.getRuntime().gc();
15515        // Delete the resources here after sending the broadcast to let
15516        // other processes clean up before deleting resources.
15517        if (info.args != null) {
15518            synchronized (mInstallLock) {
15519                info.args.doPostDeleteLI(true);
15520            }
15521        }
15522
15523        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15524    }
15525
15526    class PackageRemovedInfo {
15527        String removedPackage;
15528        int uid = -1;
15529        int removedAppId = -1;
15530        int[] origUsers;
15531        int[] removedUsers = null;
15532        boolean isRemovedPackageSystemUpdate = false;
15533        boolean isUpdate;
15534        boolean dataRemoved;
15535        boolean removedForAllUsers;
15536        // Clean up resources deleted packages.
15537        InstallArgs args = null;
15538        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15539        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15540
15541        void sendPackageRemovedBroadcasts(boolean killApp) {
15542            sendPackageRemovedBroadcastInternal(killApp);
15543            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15544            for (int i = 0; i < childCount; i++) {
15545                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15546                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15547            }
15548        }
15549
15550        void sendSystemPackageUpdatedBroadcasts() {
15551            if (isRemovedPackageSystemUpdate) {
15552                sendSystemPackageUpdatedBroadcastsInternal();
15553                final int childCount = (removedChildPackages != null)
15554                        ? removedChildPackages.size() : 0;
15555                for (int i = 0; i < childCount; i++) {
15556                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15557                    if (childInfo.isRemovedPackageSystemUpdate) {
15558                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15559                    }
15560                }
15561            }
15562        }
15563
15564        void sendSystemPackageAppearedBroadcasts() {
15565            final int packageCount = (appearedChildPackages != null)
15566                    ? appearedChildPackages.size() : 0;
15567            for (int i = 0; i < packageCount; i++) {
15568                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15569                for (int userId : installedInfo.newUsers) {
15570                    sendPackageAddedForUser(installedInfo.name, true,
15571                            UserHandle.getAppId(installedInfo.uid), userId);
15572                }
15573            }
15574        }
15575
15576        private void sendSystemPackageUpdatedBroadcastsInternal() {
15577            Bundle extras = new Bundle(2);
15578            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15579            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15580            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15581                    extras, 0, null, null, null);
15582            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15583                    extras, 0, null, null, null);
15584            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15585                    null, 0, removedPackage, null, null);
15586        }
15587
15588        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15589            Bundle extras = new Bundle(2);
15590            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15591            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15592            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15593            if (isUpdate || isRemovedPackageSystemUpdate) {
15594                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15595            }
15596            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15597            if (removedPackage != null) {
15598                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15599                        extras, 0, null, null, removedUsers);
15600                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15601                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15602                            removedPackage, extras, 0, null, null, removedUsers);
15603                }
15604            }
15605            if (removedAppId >= 0) {
15606                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15607                        removedUsers);
15608            }
15609        }
15610    }
15611
15612    /*
15613     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15614     * flag is not set, the data directory is removed as well.
15615     * make sure this flag is set for partially installed apps. If not its meaningless to
15616     * delete a partially installed application.
15617     */
15618    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15619            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15620        String packageName = ps.name;
15621        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15622        // Retrieve object to delete permissions for shared user later on
15623        final PackageParser.Package deletedPkg;
15624        final PackageSetting deletedPs;
15625        // reader
15626        synchronized (mPackages) {
15627            deletedPkg = mPackages.get(packageName);
15628            deletedPs = mSettings.mPackages.get(packageName);
15629            if (outInfo != null) {
15630                outInfo.removedPackage = packageName;
15631                outInfo.removedUsers = deletedPs != null
15632                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15633                        : null;
15634            }
15635        }
15636
15637        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15638
15639        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15640            final PackageParser.Package resolvedPkg;
15641            if (deletedPkg != null) {
15642                resolvedPkg = deletedPkg;
15643            } else {
15644                // We don't have a parsed package when it lives on an ejected
15645                // adopted storage device, so fake something together
15646                resolvedPkg = new PackageParser.Package(ps.name);
15647                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15648            }
15649            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15650                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15651            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15652            if (outInfo != null) {
15653                outInfo.dataRemoved = true;
15654            }
15655            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15656        }
15657
15658        // writer
15659        synchronized (mPackages) {
15660            if (deletedPs != null) {
15661                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15662                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15663                    clearDefaultBrowserIfNeeded(packageName);
15664                    if (outInfo != null) {
15665                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15666                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15667                    }
15668                    updatePermissionsLPw(deletedPs.name, null, 0);
15669                    if (deletedPs.sharedUser != null) {
15670                        // Remove permissions associated with package. Since runtime
15671                        // permissions are per user we have to kill the removed package
15672                        // or packages running under the shared user of the removed
15673                        // package if revoking the permissions requested only by the removed
15674                        // package is successful and this causes a change in gids.
15675                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15676                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15677                                    userId);
15678                            if (userIdToKill == UserHandle.USER_ALL
15679                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15680                                // If gids changed for this user, kill all affected packages.
15681                                mHandler.post(new Runnable() {
15682                                    @Override
15683                                    public void run() {
15684                                        // This has to happen with no lock held.
15685                                        killApplication(deletedPs.name, deletedPs.appId,
15686                                                KILL_APP_REASON_GIDS_CHANGED);
15687                                    }
15688                                });
15689                                break;
15690                            }
15691                        }
15692                    }
15693                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15694                }
15695                // make sure to preserve per-user disabled state if this removal was just
15696                // a downgrade of a system app to the factory package
15697                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15698                    if (DEBUG_REMOVE) {
15699                        Slog.d(TAG, "Propagating install state across downgrade");
15700                    }
15701                    for (int userId : allUserHandles) {
15702                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15703                        if (DEBUG_REMOVE) {
15704                            Slog.d(TAG, "    user " + userId + " => " + installed);
15705                        }
15706                        ps.setInstalled(installed, userId);
15707                    }
15708                }
15709            }
15710            // can downgrade to reader
15711            if (writeSettings) {
15712                // Save settings now
15713                mSettings.writeLPr();
15714            }
15715        }
15716        if (outInfo != null) {
15717            // A user ID was deleted here. Go through all users and remove it
15718            // from KeyStore.
15719            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15720        }
15721    }
15722
15723    static boolean locationIsPrivileged(File path) {
15724        try {
15725            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15726                    .getCanonicalPath();
15727            return path.getCanonicalPath().startsWith(privilegedAppDir);
15728        } catch (IOException e) {
15729            Slog.e(TAG, "Unable to access code path " + path);
15730        }
15731        return false;
15732    }
15733
15734    /*
15735     * Tries to delete system package.
15736     */
15737    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15738            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15739            boolean writeSettings) {
15740        if (deletedPs.parentPackageName != null) {
15741            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15742            return false;
15743        }
15744
15745        final boolean applyUserRestrictions
15746                = (allUserHandles != null) && (outInfo.origUsers != null);
15747        final PackageSetting disabledPs;
15748        // Confirm if the system package has been updated
15749        // An updated system app can be deleted. This will also have to restore
15750        // the system pkg from system partition
15751        // reader
15752        synchronized (mPackages) {
15753            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15754        }
15755
15756        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15757                + " disabledPs=" + disabledPs);
15758
15759        if (disabledPs == null) {
15760            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15761            return false;
15762        } else if (DEBUG_REMOVE) {
15763            Slog.d(TAG, "Deleting system pkg from data partition");
15764        }
15765
15766        if (DEBUG_REMOVE) {
15767            if (applyUserRestrictions) {
15768                Slog.d(TAG, "Remembering install states:");
15769                for (int userId : allUserHandles) {
15770                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15771                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15772                }
15773            }
15774        }
15775
15776        // Delete the updated package
15777        outInfo.isRemovedPackageSystemUpdate = true;
15778        if (outInfo.removedChildPackages != null) {
15779            final int childCount = (deletedPs.childPackageNames != null)
15780                    ? deletedPs.childPackageNames.size() : 0;
15781            for (int i = 0; i < childCount; i++) {
15782                String childPackageName = deletedPs.childPackageNames.get(i);
15783                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15784                        .contains(childPackageName)) {
15785                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15786                            childPackageName);
15787                    if (childInfo != null) {
15788                        childInfo.isRemovedPackageSystemUpdate = true;
15789                    }
15790                }
15791            }
15792        }
15793
15794        if (disabledPs.versionCode < deletedPs.versionCode) {
15795            // Delete data for downgrades
15796            flags &= ~PackageManager.DELETE_KEEP_DATA;
15797        } else {
15798            // Preserve data by setting flag
15799            flags |= PackageManager.DELETE_KEEP_DATA;
15800        }
15801
15802        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15803                outInfo, writeSettings, disabledPs.pkg);
15804        if (!ret) {
15805            return false;
15806        }
15807
15808        // writer
15809        synchronized (mPackages) {
15810            // Reinstate the old system package
15811            enableSystemPackageLPw(disabledPs.pkg);
15812            // Remove any native libraries from the upgraded package.
15813            removeNativeBinariesLI(deletedPs);
15814        }
15815
15816        // Install the system package
15817        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15818        int parseFlags = mDefParseFlags
15819                | PackageParser.PARSE_MUST_BE_APK
15820                | PackageParser.PARSE_IS_SYSTEM
15821                | PackageParser.PARSE_IS_SYSTEM_DIR;
15822        if (locationIsPrivileged(disabledPs.codePath)) {
15823            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15824        }
15825
15826        final PackageParser.Package newPkg;
15827        try {
15828            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15829        } catch (PackageManagerException e) {
15830            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15831                    + e.getMessage());
15832            return false;
15833        }
15834        try {
15835            // update shared libraries for the newly re-installed system package
15836            updateSharedLibrariesLPw(newPkg, null);
15837        } catch (PackageManagerException e) {
15838            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
15839        }
15840
15841        prepareAppDataAfterInstallLIF(newPkg);
15842
15843        // writer
15844        synchronized (mPackages) {
15845            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15846
15847            // Propagate the permissions state as we do not want to drop on the floor
15848            // runtime permissions. The update permissions method below will take
15849            // care of removing obsolete permissions and grant install permissions.
15850            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15851            updatePermissionsLPw(newPkg.packageName, newPkg,
15852                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15853
15854            if (applyUserRestrictions) {
15855                if (DEBUG_REMOVE) {
15856                    Slog.d(TAG, "Propagating install state across reinstall");
15857                }
15858                for (int userId : allUserHandles) {
15859                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15860                    if (DEBUG_REMOVE) {
15861                        Slog.d(TAG, "    user " + userId + " => " + installed);
15862                    }
15863                    ps.setInstalled(installed, userId);
15864
15865                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15866                }
15867                // Regardless of writeSettings we need to ensure that this restriction
15868                // state propagation is persisted
15869                mSettings.writeAllUsersPackageRestrictionsLPr();
15870            }
15871            // can downgrade to reader here
15872            if (writeSettings) {
15873                mSettings.writeLPr();
15874            }
15875        }
15876        return true;
15877    }
15878
15879    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15880            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15881            PackageRemovedInfo outInfo, boolean writeSettings,
15882            PackageParser.Package replacingPackage) {
15883        synchronized (mPackages) {
15884            if (outInfo != null) {
15885                outInfo.uid = ps.appId;
15886            }
15887
15888            if (outInfo != null && outInfo.removedChildPackages != null) {
15889                final int childCount = (ps.childPackageNames != null)
15890                        ? ps.childPackageNames.size() : 0;
15891                for (int i = 0; i < childCount; i++) {
15892                    String childPackageName = ps.childPackageNames.get(i);
15893                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15894                    if (childPs == null) {
15895                        return false;
15896                    }
15897                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15898                            childPackageName);
15899                    if (childInfo != null) {
15900                        childInfo.uid = childPs.appId;
15901                    }
15902                }
15903            }
15904        }
15905
15906        // Delete package data from internal structures and also remove data if flag is set
15907        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15908
15909        // Delete the child packages data
15910        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15911        for (int i = 0; i < childCount; i++) {
15912            PackageSetting childPs;
15913            synchronized (mPackages) {
15914                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15915            }
15916            if (childPs != null) {
15917                PackageRemovedInfo childOutInfo = (outInfo != null
15918                        && outInfo.removedChildPackages != null)
15919                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15920                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15921                        && (replacingPackage != null
15922                        && !replacingPackage.hasChildPackage(childPs.name))
15923                        ? flags & ~DELETE_KEEP_DATA : flags;
15924                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15925                        deleteFlags, writeSettings);
15926            }
15927        }
15928
15929        // Delete application code and resources only for parent packages
15930        if (ps.parentPackageName == null) {
15931            if (deleteCodeAndResources && (outInfo != null)) {
15932                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15933                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15934                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15935            }
15936        }
15937
15938        return true;
15939    }
15940
15941    @Override
15942    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15943            int userId) {
15944        mContext.enforceCallingOrSelfPermission(
15945                android.Manifest.permission.DELETE_PACKAGES, null);
15946        synchronized (mPackages) {
15947            PackageSetting ps = mSettings.mPackages.get(packageName);
15948            if (ps == null) {
15949                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15950                return false;
15951            }
15952            if (!ps.getInstalled(userId)) {
15953                // Can't block uninstall for an app that is not installed or enabled.
15954                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15955                return false;
15956            }
15957            ps.setBlockUninstall(blockUninstall, userId);
15958            mSettings.writePackageRestrictionsLPr(userId);
15959        }
15960        return true;
15961    }
15962
15963    @Override
15964    public boolean getBlockUninstallForUser(String packageName, int userId) {
15965        synchronized (mPackages) {
15966            PackageSetting ps = mSettings.mPackages.get(packageName);
15967            if (ps == null) {
15968                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15969                return false;
15970            }
15971            return ps.getBlockUninstall(userId);
15972        }
15973    }
15974
15975    @Override
15976    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15977        int callingUid = Binder.getCallingUid();
15978        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15979            throw new SecurityException(
15980                    "setRequiredForSystemUser can only be run by the system or root");
15981        }
15982        synchronized (mPackages) {
15983            PackageSetting ps = mSettings.mPackages.get(packageName);
15984            if (ps == null) {
15985                Log.w(TAG, "Package doesn't exist: " + packageName);
15986                return false;
15987            }
15988            if (systemUserApp) {
15989                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15990            } else {
15991                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15992            }
15993            mSettings.writeLPr();
15994        }
15995        return true;
15996    }
15997
15998    /*
15999     * This method handles package deletion in general
16000     */
16001    private boolean deletePackageLIF(String packageName, UserHandle user,
16002            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16003            PackageRemovedInfo outInfo, boolean writeSettings,
16004            PackageParser.Package replacingPackage) {
16005        if (packageName == null) {
16006            Slog.w(TAG, "Attempt to delete null packageName.");
16007            return false;
16008        }
16009
16010        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16011
16012        PackageSetting ps;
16013
16014        synchronized (mPackages) {
16015            ps = mSettings.mPackages.get(packageName);
16016            if (ps == null) {
16017                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16018                return false;
16019            }
16020
16021            if (ps.parentPackageName != null && (!isSystemApp(ps)
16022                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16023                if (DEBUG_REMOVE) {
16024                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16025                            + ((user == null) ? UserHandle.USER_ALL : user));
16026                }
16027                final int removedUserId = (user != null) ? user.getIdentifier()
16028                        : UserHandle.USER_ALL;
16029                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16030                    return false;
16031                }
16032                markPackageUninstalledForUserLPw(ps, user);
16033                scheduleWritePackageRestrictionsLocked(user);
16034                return true;
16035            }
16036        }
16037
16038        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16039                && user.getIdentifier() != UserHandle.USER_ALL)) {
16040            // The caller is asking that the package only be deleted for a single
16041            // user.  To do this, we just mark its uninstalled state and delete
16042            // its data. If this is a system app, we only allow this to happen if
16043            // they have set the special DELETE_SYSTEM_APP which requests different
16044            // semantics than normal for uninstalling system apps.
16045            markPackageUninstalledForUserLPw(ps, user);
16046
16047            if (!isSystemApp(ps)) {
16048                // Do not uninstall the APK if an app should be cached
16049                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16050                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16051                    // Other user still have this package installed, so all
16052                    // we need to do is clear this user's data and save that
16053                    // it is uninstalled.
16054                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16055                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16056                        return false;
16057                    }
16058                    scheduleWritePackageRestrictionsLocked(user);
16059                    return true;
16060                } else {
16061                    // We need to set it back to 'installed' so the uninstall
16062                    // broadcasts will be sent correctly.
16063                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16064                    ps.setInstalled(true, user.getIdentifier());
16065                }
16066            } else {
16067                // This is a system app, so we assume that the
16068                // other users still have this package installed, so all
16069                // we need to do is clear this user's data and save that
16070                // it is uninstalled.
16071                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16072                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16073                    return false;
16074                }
16075                scheduleWritePackageRestrictionsLocked(user);
16076                return true;
16077            }
16078        }
16079
16080        // If we are deleting a composite package for all users, keep track
16081        // of result for each child.
16082        if (ps.childPackageNames != null && outInfo != null) {
16083            synchronized (mPackages) {
16084                final int childCount = ps.childPackageNames.size();
16085                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16086                for (int i = 0; i < childCount; i++) {
16087                    String childPackageName = ps.childPackageNames.get(i);
16088                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16089                    childInfo.removedPackage = childPackageName;
16090                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16091                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16092                    if (childPs != null) {
16093                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16094                    }
16095                }
16096            }
16097        }
16098
16099        boolean ret = false;
16100        if (isSystemApp(ps)) {
16101            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16102            // When an updated system application is deleted we delete the existing resources
16103            // as well and fall back to existing code in system partition
16104            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16105        } else {
16106            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16107            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16108                    outInfo, writeSettings, replacingPackage);
16109        }
16110
16111        // Take a note whether we deleted the package for all users
16112        if (outInfo != null) {
16113            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16114            if (outInfo.removedChildPackages != null) {
16115                synchronized (mPackages) {
16116                    final int childCount = outInfo.removedChildPackages.size();
16117                    for (int i = 0; i < childCount; i++) {
16118                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16119                        if (childInfo != null) {
16120                            childInfo.removedForAllUsers = mPackages.get(
16121                                    childInfo.removedPackage) == null;
16122                        }
16123                    }
16124                }
16125            }
16126            // If we uninstalled an update to a system app there may be some
16127            // child packages that appeared as they are declared in the system
16128            // app but were not declared in the update.
16129            if (isSystemApp(ps)) {
16130                synchronized (mPackages) {
16131                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16132                    final int childCount = (updatedPs.childPackageNames != null)
16133                            ? updatedPs.childPackageNames.size() : 0;
16134                    for (int i = 0; i < childCount; i++) {
16135                        String childPackageName = updatedPs.childPackageNames.get(i);
16136                        if (outInfo.removedChildPackages == null
16137                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16138                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16139                            if (childPs == null) {
16140                                continue;
16141                            }
16142                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16143                            installRes.name = childPackageName;
16144                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16145                            installRes.pkg = mPackages.get(childPackageName);
16146                            installRes.uid = childPs.pkg.applicationInfo.uid;
16147                            if (outInfo.appearedChildPackages == null) {
16148                                outInfo.appearedChildPackages = new ArrayMap<>();
16149                            }
16150                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16151                        }
16152                    }
16153                }
16154            }
16155        }
16156
16157        return ret;
16158    }
16159
16160    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16161        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16162                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16163        for (int nextUserId : userIds) {
16164            if (DEBUG_REMOVE) {
16165                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16166            }
16167            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16168                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16169                    false /*hidden*/, false /*suspended*/, null, null, null,
16170                    false /*blockUninstall*/,
16171                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16172        }
16173    }
16174
16175    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16176            PackageRemovedInfo outInfo) {
16177        final PackageParser.Package pkg;
16178        synchronized (mPackages) {
16179            pkg = mPackages.get(ps.name);
16180        }
16181
16182        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16183                : new int[] {userId};
16184        for (int nextUserId : userIds) {
16185            if (DEBUG_REMOVE) {
16186                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16187                        + nextUserId);
16188            }
16189
16190            destroyAppDataLIF(pkg, userId,
16191                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16192            destroyAppProfilesLIF(pkg, userId);
16193            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16194            schedulePackageCleaning(ps.name, nextUserId, false);
16195            synchronized (mPackages) {
16196                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16197                    scheduleWritePackageRestrictionsLocked(nextUserId);
16198                }
16199                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16200            }
16201        }
16202
16203        if (outInfo != null) {
16204            outInfo.removedPackage = ps.name;
16205            outInfo.removedAppId = ps.appId;
16206            outInfo.removedUsers = userIds;
16207        }
16208
16209        return true;
16210    }
16211
16212    private final class ClearStorageConnection implements ServiceConnection {
16213        IMediaContainerService mContainerService;
16214
16215        @Override
16216        public void onServiceConnected(ComponentName name, IBinder service) {
16217            synchronized (this) {
16218                mContainerService = IMediaContainerService.Stub.asInterface(service);
16219                notifyAll();
16220            }
16221        }
16222
16223        @Override
16224        public void onServiceDisconnected(ComponentName name) {
16225        }
16226    }
16227
16228    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16229        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16230
16231        final boolean mounted;
16232        if (Environment.isExternalStorageEmulated()) {
16233            mounted = true;
16234        } else {
16235            final String status = Environment.getExternalStorageState();
16236
16237            mounted = status.equals(Environment.MEDIA_MOUNTED)
16238                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16239        }
16240
16241        if (!mounted) {
16242            return;
16243        }
16244
16245        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16246        int[] users;
16247        if (userId == UserHandle.USER_ALL) {
16248            users = sUserManager.getUserIds();
16249        } else {
16250            users = new int[] { userId };
16251        }
16252        final ClearStorageConnection conn = new ClearStorageConnection();
16253        if (mContext.bindServiceAsUser(
16254                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16255            try {
16256                for (int curUser : users) {
16257                    long timeout = SystemClock.uptimeMillis() + 5000;
16258                    synchronized (conn) {
16259                        long now;
16260                        while (conn.mContainerService == null &&
16261                                (now = SystemClock.uptimeMillis()) < timeout) {
16262                            try {
16263                                conn.wait(timeout - now);
16264                            } catch (InterruptedException e) {
16265                            }
16266                        }
16267                    }
16268                    if (conn.mContainerService == null) {
16269                        return;
16270                    }
16271
16272                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16273                    clearDirectory(conn.mContainerService,
16274                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16275                    if (allData) {
16276                        clearDirectory(conn.mContainerService,
16277                                userEnv.buildExternalStorageAppDataDirs(packageName));
16278                        clearDirectory(conn.mContainerService,
16279                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16280                    }
16281                }
16282            } finally {
16283                mContext.unbindService(conn);
16284            }
16285        }
16286    }
16287
16288    @Override
16289    public void clearApplicationProfileData(String packageName) {
16290        enforceSystemOrRoot("Only the system can clear all profile data");
16291
16292        final PackageParser.Package pkg;
16293        synchronized (mPackages) {
16294            pkg = mPackages.get(packageName);
16295        }
16296
16297        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16298            synchronized (mInstallLock) {
16299                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16300                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16301                        true /* removeBaseMarker */);
16302            }
16303        }
16304    }
16305
16306    @Override
16307    public void clearApplicationUserData(final String packageName,
16308            final IPackageDataObserver observer, final int userId) {
16309        mContext.enforceCallingOrSelfPermission(
16310                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16311
16312        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16313                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16314
16315        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16316            throw new SecurityException("Cannot clear data for a protected package: "
16317                    + packageName);
16318        }
16319        // Queue up an async operation since the package deletion may take a little while.
16320        mHandler.post(new Runnable() {
16321            public void run() {
16322                mHandler.removeCallbacks(this);
16323                final boolean succeeded;
16324                try (PackageFreezer freezer = freezePackage(packageName,
16325                        "clearApplicationUserData")) {
16326                    synchronized (mInstallLock) {
16327                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16328                    }
16329                    clearExternalStorageDataSync(packageName, userId, true);
16330                }
16331                if (succeeded) {
16332                    // invoke DeviceStorageMonitor's update method to clear any notifications
16333                    DeviceStorageMonitorInternal dsm = LocalServices
16334                            .getService(DeviceStorageMonitorInternal.class);
16335                    if (dsm != null) {
16336                        dsm.checkMemory();
16337                    }
16338                }
16339                if(observer != null) {
16340                    try {
16341                        observer.onRemoveCompleted(packageName, succeeded);
16342                    } catch (RemoteException e) {
16343                        Log.i(TAG, "Observer no longer exists.");
16344                    }
16345                } //end if observer
16346            } //end run
16347        });
16348    }
16349
16350    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16351        if (packageName == null) {
16352            Slog.w(TAG, "Attempt to delete null packageName.");
16353            return false;
16354        }
16355
16356        // Try finding details about the requested package
16357        PackageParser.Package pkg;
16358        synchronized (mPackages) {
16359            pkg = mPackages.get(packageName);
16360            if (pkg == null) {
16361                final PackageSetting ps = mSettings.mPackages.get(packageName);
16362                if (ps != null) {
16363                    pkg = ps.pkg;
16364                }
16365            }
16366
16367            if (pkg == null) {
16368                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16369                return false;
16370            }
16371
16372            PackageSetting ps = (PackageSetting) pkg.mExtras;
16373            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16374        }
16375
16376        clearAppDataLIF(pkg, userId,
16377                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16378
16379        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16380        removeKeystoreDataIfNeeded(userId, appId);
16381
16382        UserManagerInternal umInternal = getUserManagerInternal();
16383        final int flags;
16384        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16385            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16386        } else if (umInternal.isUserRunning(userId)) {
16387            flags = StorageManager.FLAG_STORAGE_DE;
16388        } else {
16389            flags = 0;
16390        }
16391        prepareAppDataContentsLIF(pkg, userId, flags);
16392
16393        return true;
16394    }
16395
16396    /**
16397     * Reverts user permission state changes (permissions and flags) in
16398     * all packages for a given user.
16399     *
16400     * @param userId The device user for which to do a reset.
16401     */
16402    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16403        final int packageCount = mPackages.size();
16404        for (int i = 0; i < packageCount; i++) {
16405            PackageParser.Package pkg = mPackages.valueAt(i);
16406            PackageSetting ps = (PackageSetting) pkg.mExtras;
16407            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16408        }
16409    }
16410
16411    private void resetNetworkPolicies(int userId) {
16412        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16413    }
16414
16415    /**
16416     * Reverts user permission state changes (permissions and flags).
16417     *
16418     * @param ps The package for which to reset.
16419     * @param userId The device user for which to do a reset.
16420     */
16421    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16422            final PackageSetting ps, final int userId) {
16423        if (ps.pkg == null) {
16424            return;
16425        }
16426
16427        // These are flags that can change base on user actions.
16428        final int userSettableMask = FLAG_PERMISSION_USER_SET
16429                | FLAG_PERMISSION_USER_FIXED
16430                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16431                | FLAG_PERMISSION_REVIEW_REQUIRED;
16432
16433        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16434                | FLAG_PERMISSION_POLICY_FIXED;
16435
16436        boolean writeInstallPermissions = false;
16437        boolean writeRuntimePermissions = false;
16438
16439        final int permissionCount = ps.pkg.requestedPermissions.size();
16440        for (int i = 0; i < permissionCount; i++) {
16441            String permission = ps.pkg.requestedPermissions.get(i);
16442
16443            BasePermission bp = mSettings.mPermissions.get(permission);
16444            if (bp == null) {
16445                continue;
16446            }
16447
16448            // If shared user we just reset the state to which only this app contributed.
16449            if (ps.sharedUser != null) {
16450                boolean used = false;
16451                final int packageCount = ps.sharedUser.packages.size();
16452                for (int j = 0; j < packageCount; j++) {
16453                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16454                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16455                            && pkg.pkg.requestedPermissions.contains(permission)) {
16456                        used = true;
16457                        break;
16458                    }
16459                }
16460                if (used) {
16461                    continue;
16462                }
16463            }
16464
16465            PermissionsState permissionsState = ps.getPermissionsState();
16466
16467            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16468
16469            // Always clear the user settable flags.
16470            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16471                    bp.name) != null;
16472            // If permission review is enabled and this is a legacy app, mark the
16473            // permission as requiring a review as this is the initial state.
16474            int flags = 0;
16475            if (Build.PERMISSIONS_REVIEW_REQUIRED
16476                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16477                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16478            }
16479            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16480                if (hasInstallState) {
16481                    writeInstallPermissions = true;
16482                } else {
16483                    writeRuntimePermissions = true;
16484                }
16485            }
16486
16487            // Below is only runtime permission handling.
16488            if (!bp.isRuntime()) {
16489                continue;
16490            }
16491
16492            // Never clobber system or policy.
16493            if ((oldFlags & policyOrSystemFlags) != 0) {
16494                continue;
16495            }
16496
16497            // If this permission was granted by default, make sure it is.
16498            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16499                if (permissionsState.grantRuntimePermission(bp, userId)
16500                        != PERMISSION_OPERATION_FAILURE) {
16501                    writeRuntimePermissions = true;
16502                }
16503            // If permission review is enabled the permissions for a legacy apps
16504            // are represented as constantly granted runtime ones, so don't revoke.
16505            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16506                // Otherwise, reset the permission.
16507                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16508                switch (revokeResult) {
16509                    case PERMISSION_OPERATION_SUCCESS:
16510                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16511                        writeRuntimePermissions = true;
16512                        final int appId = ps.appId;
16513                        mHandler.post(new Runnable() {
16514                            @Override
16515                            public void run() {
16516                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16517                            }
16518                        });
16519                    } break;
16520                }
16521            }
16522        }
16523
16524        // Synchronously write as we are taking permissions away.
16525        if (writeRuntimePermissions) {
16526            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16527        }
16528
16529        // Synchronously write as we are taking permissions away.
16530        if (writeInstallPermissions) {
16531            mSettings.writeLPr();
16532        }
16533    }
16534
16535    /**
16536     * Remove entries from the keystore daemon. Will only remove it if the
16537     * {@code appId} is valid.
16538     */
16539    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16540        if (appId < 0) {
16541            return;
16542        }
16543
16544        final KeyStore keyStore = KeyStore.getInstance();
16545        if (keyStore != null) {
16546            if (userId == UserHandle.USER_ALL) {
16547                for (final int individual : sUserManager.getUserIds()) {
16548                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16549                }
16550            } else {
16551                keyStore.clearUid(UserHandle.getUid(userId, appId));
16552            }
16553        } else {
16554            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16555        }
16556    }
16557
16558    @Override
16559    public void deleteApplicationCacheFiles(final String packageName,
16560            final IPackageDataObserver observer) {
16561        final int userId = UserHandle.getCallingUserId();
16562        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16563    }
16564
16565    @Override
16566    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16567            final IPackageDataObserver observer) {
16568        mContext.enforceCallingOrSelfPermission(
16569                android.Manifest.permission.DELETE_CACHE_FILES, null);
16570        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16571                /* requireFullPermission= */ true, /* checkShell= */ false,
16572                "delete application cache files");
16573
16574        final PackageParser.Package pkg;
16575        synchronized (mPackages) {
16576            pkg = mPackages.get(packageName);
16577        }
16578
16579        // Queue up an async operation since the package deletion may take a little while.
16580        mHandler.post(new Runnable() {
16581            public void run() {
16582                synchronized (mInstallLock) {
16583                    final int flags = StorageManager.FLAG_STORAGE_DE
16584                            | StorageManager.FLAG_STORAGE_CE;
16585                    // We're only clearing cache files, so we don't care if the
16586                    // app is unfrozen and still able to run
16587                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16588                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16589                }
16590                clearExternalStorageDataSync(packageName, userId, false);
16591                if (observer != null) {
16592                    try {
16593                        observer.onRemoveCompleted(packageName, true);
16594                    } catch (RemoteException e) {
16595                        Log.i(TAG, "Observer no longer exists.");
16596                    }
16597                }
16598            }
16599        });
16600    }
16601
16602    @Override
16603    public void getPackageSizeInfo(final String packageName, int userHandle,
16604            final IPackageStatsObserver observer) {
16605        mContext.enforceCallingOrSelfPermission(
16606                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16607        if (packageName == null) {
16608            throw new IllegalArgumentException("Attempt to get size of null packageName");
16609        }
16610
16611        PackageStats stats = new PackageStats(packageName, userHandle);
16612
16613        /*
16614         * Queue up an async operation since the package measurement may take a
16615         * little while.
16616         */
16617        Message msg = mHandler.obtainMessage(INIT_COPY);
16618        msg.obj = new MeasureParams(stats, observer);
16619        mHandler.sendMessage(msg);
16620    }
16621
16622    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16623        final PackageSetting ps;
16624        synchronized (mPackages) {
16625            ps = mSettings.mPackages.get(packageName);
16626            if (ps == null) {
16627                Slog.w(TAG, "Failed to find settings for " + packageName);
16628                return false;
16629            }
16630        }
16631        try {
16632            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16633                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16634                    ps.getCeDataInode(userId), ps.codePathString, stats);
16635        } catch (InstallerException e) {
16636            Slog.w(TAG, String.valueOf(e));
16637            return false;
16638        }
16639
16640        // For now, ignore code size of packages on system partition
16641        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16642            stats.codeSize = 0;
16643        }
16644
16645        return true;
16646    }
16647
16648    private int getUidTargetSdkVersionLockedLPr(int uid) {
16649        Object obj = mSettings.getUserIdLPr(uid);
16650        if (obj instanceof SharedUserSetting) {
16651            final SharedUserSetting sus = (SharedUserSetting) obj;
16652            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16653            final Iterator<PackageSetting> it = sus.packages.iterator();
16654            while (it.hasNext()) {
16655                final PackageSetting ps = it.next();
16656                if (ps.pkg != null) {
16657                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16658                    if (v < vers) vers = v;
16659                }
16660            }
16661            return vers;
16662        } else if (obj instanceof PackageSetting) {
16663            final PackageSetting ps = (PackageSetting) obj;
16664            if (ps.pkg != null) {
16665                return ps.pkg.applicationInfo.targetSdkVersion;
16666            }
16667        }
16668        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16669    }
16670
16671    @Override
16672    public void addPreferredActivity(IntentFilter filter, int match,
16673            ComponentName[] set, ComponentName activity, int userId) {
16674        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16675                "Adding preferred");
16676    }
16677
16678    private void addPreferredActivityInternal(IntentFilter filter, int match,
16679            ComponentName[] set, ComponentName activity, boolean always, int userId,
16680            String opname) {
16681        // writer
16682        int callingUid = Binder.getCallingUid();
16683        enforceCrossUserPermission(callingUid, userId,
16684                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16685        if (filter.countActions() == 0) {
16686            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16687            return;
16688        }
16689        synchronized (mPackages) {
16690            if (mContext.checkCallingOrSelfPermission(
16691                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16692                    != PackageManager.PERMISSION_GRANTED) {
16693                if (getUidTargetSdkVersionLockedLPr(callingUid)
16694                        < Build.VERSION_CODES.FROYO) {
16695                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16696                            + callingUid);
16697                    return;
16698                }
16699                mContext.enforceCallingOrSelfPermission(
16700                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16701            }
16702
16703            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16704            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16705                    + userId + ":");
16706            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16707            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16708            scheduleWritePackageRestrictionsLocked(userId);
16709            postPreferredActivityChangedBroadcast(userId);
16710        }
16711    }
16712
16713    private void postPreferredActivityChangedBroadcast(int userId) {
16714        mHandler.post(() -> {
16715            final IActivityManager am = ActivityManagerNative.getDefault();
16716            if (am == null) {
16717                return;
16718            }
16719
16720            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
16721            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
16722            try {
16723                am.broadcastIntent(null, intent, null, null,
16724                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
16725                        null, false, false, userId);
16726            } catch (RemoteException e) {
16727            }
16728        });
16729    }
16730
16731    @Override
16732    public void replacePreferredActivity(IntentFilter filter, int match,
16733            ComponentName[] set, ComponentName activity, int userId) {
16734        if (filter.countActions() != 1) {
16735            throw new IllegalArgumentException(
16736                    "replacePreferredActivity expects filter to have only 1 action.");
16737        }
16738        if (filter.countDataAuthorities() != 0
16739                || filter.countDataPaths() != 0
16740                || filter.countDataSchemes() > 1
16741                || filter.countDataTypes() != 0) {
16742            throw new IllegalArgumentException(
16743                    "replacePreferredActivity expects filter to have no data authorities, " +
16744                    "paths, or types; and at most one scheme.");
16745        }
16746
16747        final int callingUid = Binder.getCallingUid();
16748        enforceCrossUserPermission(callingUid, userId,
16749                true /* requireFullPermission */, false /* checkShell */,
16750                "replace preferred activity");
16751        synchronized (mPackages) {
16752            if (mContext.checkCallingOrSelfPermission(
16753                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16754                    != PackageManager.PERMISSION_GRANTED) {
16755                if (getUidTargetSdkVersionLockedLPr(callingUid)
16756                        < Build.VERSION_CODES.FROYO) {
16757                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16758                            + Binder.getCallingUid());
16759                    return;
16760                }
16761                mContext.enforceCallingOrSelfPermission(
16762                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16763            }
16764
16765            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16766            if (pir != null) {
16767                // Get all of the existing entries that exactly match this filter.
16768                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16769                if (existing != null && existing.size() == 1) {
16770                    PreferredActivity cur = existing.get(0);
16771                    if (DEBUG_PREFERRED) {
16772                        Slog.i(TAG, "Checking replace of preferred:");
16773                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16774                        if (!cur.mPref.mAlways) {
16775                            Slog.i(TAG, "  -- CUR; not mAlways!");
16776                        } else {
16777                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16778                            Slog.i(TAG, "  -- CUR: mSet="
16779                                    + Arrays.toString(cur.mPref.mSetComponents));
16780                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16781                            Slog.i(TAG, "  -- NEW: mMatch="
16782                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16783                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16784                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16785                        }
16786                    }
16787                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16788                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16789                            && cur.mPref.sameSet(set)) {
16790                        // Setting the preferred activity to what it happens to be already
16791                        if (DEBUG_PREFERRED) {
16792                            Slog.i(TAG, "Replacing with same preferred activity "
16793                                    + cur.mPref.mShortComponent + " for user "
16794                                    + userId + ":");
16795                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16796                        }
16797                        return;
16798                    }
16799                }
16800
16801                if (existing != null) {
16802                    if (DEBUG_PREFERRED) {
16803                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16804                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16805                    }
16806                    for (int i = 0; i < existing.size(); i++) {
16807                        PreferredActivity pa = existing.get(i);
16808                        if (DEBUG_PREFERRED) {
16809                            Slog.i(TAG, "Removing existing preferred activity "
16810                                    + pa.mPref.mComponent + ":");
16811                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16812                        }
16813                        pir.removeFilter(pa);
16814                    }
16815                }
16816            }
16817            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16818                    "Replacing preferred");
16819        }
16820    }
16821
16822    @Override
16823    public void clearPackagePreferredActivities(String packageName) {
16824        final int uid = Binder.getCallingUid();
16825        // writer
16826        synchronized (mPackages) {
16827            PackageParser.Package pkg = mPackages.get(packageName);
16828            if (pkg == null || pkg.applicationInfo.uid != uid) {
16829                if (mContext.checkCallingOrSelfPermission(
16830                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16831                        != PackageManager.PERMISSION_GRANTED) {
16832                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16833                            < Build.VERSION_CODES.FROYO) {
16834                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16835                                + Binder.getCallingUid());
16836                        return;
16837                    }
16838                    mContext.enforceCallingOrSelfPermission(
16839                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16840                }
16841            }
16842
16843            int user = UserHandle.getCallingUserId();
16844            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16845                scheduleWritePackageRestrictionsLocked(user);
16846            }
16847        }
16848    }
16849
16850    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16851    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16852        ArrayList<PreferredActivity> removed = null;
16853        boolean changed = false;
16854        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16855            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16856            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16857            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16858                continue;
16859            }
16860            Iterator<PreferredActivity> it = pir.filterIterator();
16861            while (it.hasNext()) {
16862                PreferredActivity pa = it.next();
16863                // Mark entry for removal only if it matches the package name
16864                // and the entry is of type "always".
16865                if (packageName == null ||
16866                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16867                                && pa.mPref.mAlways)) {
16868                    if (removed == null) {
16869                        removed = new ArrayList<PreferredActivity>();
16870                    }
16871                    removed.add(pa);
16872                }
16873            }
16874            if (removed != null) {
16875                for (int j=0; j<removed.size(); j++) {
16876                    PreferredActivity pa = removed.get(j);
16877                    pir.removeFilter(pa);
16878                }
16879                changed = true;
16880            }
16881        }
16882        if (changed) {
16883            postPreferredActivityChangedBroadcast(userId);
16884        }
16885        return changed;
16886    }
16887
16888    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16889    private void clearIntentFilterVerificationsLPw(int userId) {
16890        final int packageCount = mPackages.size();
16891        for (int i = 0; i < packageCount; i++) {
16892            PackageParser.Package pkg = mPackages.valueAt(i);
16893            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16894        }
16895    }
16896
16897    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16898    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16899        if (userId == UserHandle.USER_ALL) {
16900            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16901                    sUserManager.getUserIds())) {
16902                for (int oneUserId : sUserManager.getUserIds()) {
16903                    scheduleWritePackageRestrictionsLocked(oneUserId);
16904                }
16905            }
16906        } else {
16907            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16908                scheduleWritePackageRestrictionsLocked(userId);
16909            }
16910        }
16911    }
16912
16913    void clearDefaultBrowserIfNeeded(String packageName) {
16914        for (int oneUserId : sUserManager.getUserIds()) {
16915            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16916            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16917            if (packageName.equals(defaultBrowserPackageName)) {
16918                setDefaultBrowserPackageName(null, oneUserId);
16919            }
16920        }
16921    }
16922
16923    @Override
16924    public void resetApplicationPreferences(int userId) {
16925        mContext.enforceCallingOrSelfPermission(
16926                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16927        final long identity = Binder.clearCallingIdentity();
16928        // writer
16929        try {
16930            synchronized (mPackages) {
16931                clearPackagePreferredActivitiesLPw(null, userId);
16932                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16933                // TODO: We have to reset the default SMS and Phone. This requires
16934                // significant refactoring to keep all default apps in the package
16935                // manager (cleaner but more work) or have the services provide
16936                // callbacks to the package manager to request a default app reset.
16937                applyFactoryDefaultBrowserLPw(userId);
16938                clearIntentFilterVerificationsLPw(userId);
16939                primeDomainVerificationsLPw(userId);
16940                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16941                scheduleWritePackageRestrictionsLocked(userId);
16942            }
16943            resetNetworkPolicies(userId);
16944        } finally {
16945            Binder.restoreCallingIdentity(identity);
16946        }
16947    }
16948
16949    @Override
16950    public int getPreferredActivities(List<IntentFilter> outFilters,
16951            List<ComponentName> outActivities, String packageName) {
16952
16953        int num = 0;
16954        final int userId = UserHandle.getCallingUserId();
16955        // reader
16956        synchronized (mPackages) {
16957            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16958            if (pir != null) {
16959                final Iterator<PreferredActivity> it = pir.filterIterator();
16960                while (it.hasNext()) {
16961                    final PreferredActivity pa = it.next();
16962                    if (packageName == null
16963                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16964                                    && pa.mPref.mAlways)) {
16965                        if (outFilters != null) {
16966                            outFilters.add(new IntentFilter(pa));
16967                        }
16968                        if (outActivities != null) {
16969                            outActivities.add(pa.mPref.mComponent);
16970                        }
16971                    }
16972                }
16973            }
16974        }
16975
16976        return num;
16977    }
16978
16979    @Override
16980    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16981            int userId) {
16982        int callingUid = Binder.getCallingUid();
16983        if (callingUid != Process.SYSTEM_UID) {
16984            throw new SecurityException(
16985                    "addPersistentPreferredActivity can only be run by the system");
16986        }
16987        if (filter.countActions() == 0) {
16988            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16989            return;
16990        }
16991        synchronized (mPackages) {
16992            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16993                    ":");
16994            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16995            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16996                    new PersistentPreferredActivity(filter, activity));
16997            scheduleWritePackageRestrictionsLocked(userId);
16998            postPreferredActivityChangedBroadcast(userId);
16999        }
17000    }
17001
17002    @Override
17003    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17004        int callingUid = Binder.getCallingUid();
17005        if (callingUid != Process.SYSTEM_UID) {
17006            throw new SecurityException(
17007                    "clearPackagePersistentPreferredActivities can only be run by the system");
17008        }
17009        ArrayList<PersistentPreferredActivity> removed = null;
17010        boolean changed = false;
17011        synchronized (mPackages) {
17012            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17013                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17014                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17015                        .valueAt(i);
17016                if (userId != thisUserId) {
17017                    continue;
17018                }
17019                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17020                while (it.hasNext()) {
17021                    PersistentPreferredActivity ppa = it.next();
17022                    // Mark entry for removal only if it matches the package name.
17023                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17024                        if (removed == null) {
17025                            removed = new ArrayList<PersistentPreferredActivity>();
17026                        }
17027                        removed.add(ppa);
17028                    }
17029                }
17030                if (removed != null) {
17031                    for (int j=0; j<removed.size(); j++) {
17032                        PersistentPreferredActivity ppa = removed.get(j);
17033                        ppir.removeFilter(ppa);
17034                    }
17035                    changed = true;
17036                }
17037            }
17038
17039            if (changed) {
17040                scheduleWritePackageRestrictionsLocked(userId);
17041                postPreferredActivityChangedBroadcast(userId);
17042            }
17043        }
17044    }
17045
17046    /**
17047     * Common machinery for picking apart a restored XML blob and passing
17048     * it to a caller-supplied functor to be applied to the running system.
17049     */
17050    private void restoreFromXml(XmlPullParser parser, int userId,
17051            String expectedStartTag, BlobXmlRestorer functor)
17052            throws IOException, XmlPullParserException {
17053        int type;
17054        while ((type = parser.next()) != XmlPullParser.START_TAG
17055                && type != XmlPullParser.END_DOCUMENT) {
17056        }
17057        if (type != XmlPullParser.START_TAG) {
17058            // oops didn't find a start tag?!
17059            if (DEBUG_BACKUP) {
17060                Slog.e(TAG, "Didn't find start tag during restore");
17061            }
17062            return;
17063        }
17064Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17065        // this is supposed to be TAG_PREFERRED_BACKUP
17066        if (!expectedStartTag.equals(parser.getName())) {
17067            if (DEBUG_BACKUP) {
17068                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17069            }
17070            return;
17071        }
17072
17073        // skip interfering stuff, then we're aligned with the backing implementation
17074        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17075Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17076        functor.apply(parser, userId);
17077    }
17078
17079    private interface BlobXmlRestorer {
17080        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17081    }
17082
17083    /**
17084     * Non-Binder method, support for the backup/restore mechanism: write the
17085     * full set of preferred activities in its canonical XML format.  Returns the
17086     * XML output as a byte array, or null if there is none.
17087     */
17088    @Override
17089    public byte[] getPreferredActivityBackup(int userId) {
17090        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17091            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17092        }
17093
17094        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17095        try {
17096            final XmlSerializer serializer = new FastXmlSerializer();
17097            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17098            serializer.startDocument(null, true);
17099            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17100
17101            synchronized (mPackages) {
17102                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17103            }
17104
17105            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17106            serializer.endDocument();
17107            serializer.flush();
17108        } catch (Exception e) {
17109            if (DEBUG_BACKUP) {
17110                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17111            }
17112            return null;
17113        }
17114
17115        return dataStream.toByteArray();
17116    }
17117
17118    @Override
17119    public void restorePreferredActivities(byte[] backup, int userId) {
17120        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17121            throw new SecurityException("Only the system may call restorePreferredActivities()");
17122        }
17123
17124        try {
17125            final XmlPullParser parser = Xml.newPullParser();
17126            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17127            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17128                    new BlobXmlRestorer() {
17129                        @Override
17130                        public void apply(XmlPullParser parser, int userId)
17131                                throws XmlPullParserException, IOException {
17132                            synchronized (mPackages) {
17133                                mSettings.readPreferredActivitiesLPw(parser, userId);
17134                            }
17135                        }
17136                    } );
17137        } catch (Exception e) {
17138            if (DEBUG_BACKUP) {
17139                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17140            }
17141        }
17142    }
17143
17144    /**
17145     * Non-Binder method, support for the backup/restore mechanism: write the
17146     * default browser (etc) settings in its canonical XML format.  Returns the default
17147     * browser XML representation as a byte array, or null if there is none.
17148     */
17149    @Override
17150    public byte[] getDefaultAppsBackup(int userId) {
17151        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17152            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17153        }
17154
17155        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17156        try {
17157            final XmlSerializer serializer = new FastXmlSerializer();
17158            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17159            serializer.startDocument(null, true);
17160            serializer.startTag(null, TAG_DEFAULT_APPS);
17161
17162            synchronized (mPackages) {
17163                mSettings.writeDefaultAppsLPr(serializer, userId);
17164            }
17165
17166            serializer.endTag(null, TAG_DEFAULT_APPS);
17167            serializer.endDocument();
17168            serializer.flush();
17169        } catch (Exception e) {
17170            if (DEBUG_BACKUP) {
17171                Slog.e(TAG, "Unable to write default apps for backup", e);
17172            }
17173            return null;
17174        }
17175
17176        return dataStream.toByteArray();
17177    }
17178
17179    @Override
17180    public void restoreDefaultApps(byte[] backup, int userId) {
17181        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17182            throw new SecurityException("Only the system may call restoreDefaultApps()");
17183        }
17184
17185        try {
17186            final XmlPullParser parser = Xml.newPullParser();
17187            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17188            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17189                    new BlobXmlRestorer() {
17190                        @Override
17191                        public void apply(XmlPullParser parser, int userId)
17192                                throws XmlPullParserException, IOException {
17193                            synchronized (mPackages) {
17194                                mSettings.readDefaultAppsLPw(parser, userId);
17195                            }
17196                        }
17197                    } );
17198        } catch (Exception e) {
17199            if (DEBUG_BACKUP) {
17200                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17201            }
17202        }
17203    }
17204
17205    @Override
17206    public byte[] getIntentFilterVerificationBackup(int userId) {
17207        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17208            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17209        }
17210
17211        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17212        try {
17213            final XmlSerializer serializer = new FastXmlSerializer();
17214            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17215            serializer.startDocument(null, true);
17216            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17217
17218            synchronized (mPackages) {
17219                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17220            }
17221
17222            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17223            serializer.endDocument();
17224            serializer.flush();
17225        } catch (Exception e) {
17226            if (DEBUG_BACKUP) {
17227                Slog.e(TAG, "Unable to write default apps for backup", e);
17228            }
17229            return null;
17230        }
17231
17232        return dataStream.toByteArray();
17233    }
17234
17235    @Override
17236    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17237        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17238            throw new SecurityException("Only the system may call restorePreferredActivities()");
17239        }
17240
17241        try {
17242            final XmlPullParser parser = Xml.newPullParser();
17243            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17244            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17245                    new BlobXmlRestorer() {
17246                        @Override
17247                        public void apply(XmlPullParser parser, int userId)
17248                                throws XmlPullParserException, IOException {
17249                            synchronized (mPackages) {
17250                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17251                                mSettings.writeLPr();
17252                            }
17253                        }
17254                    } );
17255        } catch (Exception e) {
17256            if (DEBUG_BACKUP) {
17257                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17258            }
17259        }
17260    }
17261
17262    @Override
17263    public byte[] getPermissionGrantBackup(int userId) {
17264        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17265            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17266        }
17267
17268        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17269        try {
17270            final XmlSerializer serializer = new FastXmlSerializer();
17271            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17272            serializer.startDocument(null, true);
17273            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17274
17275            synchronized (mPackages) {
17276                serializeRuntimePermissionGrantsLPr(serializer, userId);
17277            }
17278
17279            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17280            serializer.endDocument();
17281            serializer.flush();
17282        } catch (Exception e) {
17283            if (DEBUG_BACKUP) {
17284                Slog.e(TAG, "Unable to write default apps for backup", e);
17285            }
17286            return null;
17287        }
17288
17289        return dataStream.toByteArray();
17290    }
17291
17292    @Override
17293    public void restorePermissionGrants(byte[] backup, int userId) {
17294        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17295            throw new SecurityException("Only the system may call restorePermissionGrants()");
17296        }
17297
17298        try {
17299            final XmlPullParser parser = Xml.newPullParser();
17300            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17301            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17302                    new BlobXmlRestorer() {
17303                        @Override
17304                        public void apply(XmlPullParser parser, int userId)
17305                                throws XmlPullParserException, IOException {
17306                            synchronized (mPackages) {
17307                                processRestoredPermissionGrantsLPr(parser, userId);
17308                            }
17309                        }
17310                    } );
17311        } catch (Exception e) {
17312            if (DEBUG_BACKUP) {
17313                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17314            }
17315        }
17316    }
17317
17318    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17319            throws IOException {
17320        serializer.startTag(null, TAG_ALL_GRANTS);
17321
17322        final int N = mSettings.mPackages.size();
17323        for (int i = 0; i < N; i++) {
17324            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17325            boolean pkgGrantsKnown = false;
17326
17327            PermissionsState packagePerms = ps.getPermissionsState();
17328
17329            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17330                final int grantFlags = state.getFlags();
17331                // only look at grants that are not system/policy fixed
17332                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17333                    final boolean isGranted = state.isGranted();
17334                    // And only back up the user-twiddled state bits
17335                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17336                        final String packageName = mSettings.mPackages.keyAt(i);
17337                        if (!pkgGrantsKnown) {
17338                            serializer.startTag(null, TAG_GRANT);
17339                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17340                            pkgGrantsKnown = true;
17341                        }
17342
17343                        final boolean userSet =
17344                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17345                        final boolean userFixed =
17346                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17347                        final boolean revoke =
17348                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17349
17350                        serializer.startTag(null, TAG_PERMISSION);
17351                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17352                        if (isGranted) {
17353                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17354                        }
17355                        if (userSet) {
17356                            serializer.attribute(null, ATTR_USER_SET, "true");
17357                        }
17358                        if (userFixed) {
17359                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17360                        }
17361                        if (revoke) {
17362                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17363                        }
17364                        serializer.endTag(null, TAG_PERMISSION);
17365                    }
17366                }
17367            }
17368
17369            if (pkgGrantsKnown) {
17370                serializer.endTag(null, TAG_GRANT);
17371            }
17372        }
17373
17374        serializer.endTag(null, TAG_ALL_GRANTS);
17375    }
17376
17377    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17378            throws XmlPullParserException, IOException {
17379        String pkgName = null;
17380        int outerDepth = parser.getDepth();
17381        int type;
17382        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17383                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17384            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17385                continue;
17386            }
17387
17388            final String tagName = parser.getName();
17389            if (tagName.equals(TAG_GRANT)) {
17390                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17391                if (DEBUG_BACKUP) {
17392                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17393                }
17394            } else if (tagName.equals(TAG_PERMISSION)) {
17395
17396                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17397                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17398
17399                int newFlagSet = 0;
17400                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17401                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17402                }
17403                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17404                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17405                }
17406                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17407                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17408                }
17409                if (DEBUG_BACKUP) {
17410                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17411                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17412                }
17413                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17414                if (ps != null) {
17415                    // Already installed so we apply the grant immediately
17416                    if (DEBUG_BACKUP) {
17417                        Slog.v(TAG, "        + already installed; applying");
17418                    }
17419                    PermissionsState perms = ps.getPermissionsState();
17420                    BasePermission bp = mSettings.mPermissions.get(permName);
17421                    if (bp != null) {
17422                        if (isGranted) {
17423                            perms.grantRuntimePermission(bp, userId);
17424                        }
17425                        if (newFlagSet != 0) {
17426                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17427                        }
17428                    }
17429                } else {
17430                    // Need to wait for post-restore install to apply the grant
17431                    if (DEBUG_BACKUP) {
17432                        Slog.v(TAG, "        - not yet installed; saving for later");
17433                    }
17434                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17435                            isGranted, newFlagSet, userId);
17436                }
17437            } else {
17438                PackageManagerService.reportSettingsProblem(Log.WARN,
17439                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17440                XmlUtils.skipCurrentTag(parser);
17441            }
17442        }
17443
17444        scheduleWriteSettingsLocked();
17445        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17446    }
17447
17448    @Override
17449    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17450            int sourceUserId, int targetUserId, int flags) {
17451        mContext.enforceCallingOrSelfPermission(
17452                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17453        int callingUid = Binder.getCallingUid();
17454        enforceOwnerRights(ownerPackage, callingUid);
17455        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17456        if (intentFilter.countActions() == 0) {
17457            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17458            return;
17459        }
17460        synchronized (mPackages) {
17461            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17462                    ownerPackage, targetUserId, flags);
17463            CrossProfileIntentResolver resolver =
17464                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17465            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17466            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17467            if (existing != null) {
17468                int size = existing.size();
17469                for (int i = 0; i < size; i++) {
17470                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17471                        return;
17472                    }
17473                }
17474            }
17475            resolver.addFilter(newFilter);
17476            scheduleWritePackageRestrictionsLocked(sourceUserId);
17477        }
17478    }
17479
17480    @Override
17481    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17482        mContext.enforceCallingOrSelfPermission(
17483                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17484        int callingUid = Binder.getCallingUid();
17485        enforceOwnerRights(ownerPackage, callingUid);
17486        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17487        synchronized (mPackages) {
17488            CrossProfileIntentResolver resolver =
17489                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17490            ArraySet<CrossProfileIntentFilter> set =
17491                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17492            for (CrossProfileIntentFilter filter : set) {
17493                if (filter.getOwnerPackage().equals(ownerPackage)) {
17494                    resolver.removeFilter(filter);
17495                }
17496            }
17497            scheduleWritePackageRestrictionsLocked(sourceUserId);
17498        }
17499    }
17500
17501    // Enforcing that callingUid is owning pkg on userId
17502    private void enforceOwnerRights(String pkg, int callingUid) {
17503        // The system owns everything.
17504        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17505            return;
17506        }
17507        int callingUserId = UserHandle.getUserId(callingUid);
17508        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17509        if (pi == null) {
17510            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17511                    + callingUserId);
17512        }
17513        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17514            throw new SecurityException("Calling uid " + callingUid
17515                    + " does not own package " + pkg);
17516        }
17517    }
17518
17519    @Override
17520    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17521        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17522    }
17523
17524    private Intent getHomeIntent() {
17525        Intent intent = new Intent(Intent.ACTION_MAIN);
17526        intent.addCategory(Intent.CATEGORY_HOME);
17527        intent.addCategory(Intent.CATEGORY_DEFAULT);
17528        return intent;
17529    }
17530
17531    private IntentFilter getHomeFilter() {
17532        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17533        filter.addCategory(Intent.CATEGORY_HOME);
17534        filter.addCategory(Intent.CATEGORY_DEFAULT);
17535        return filter;
17536    }
17537
17538    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17539            int userId) {
17540        Intent intent  = getHomeIntent();
17541        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17542                PackageManager.GET_META_DATA, userId);
17543        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17544                true, false, false, userId);
17545
17546        allHomeCandidates.clear();
17547        if (list != null) {
17548            for (ResolveInfo ri : list) {
17549                allHomeCandidates.add(ri);
17550            }
17551        }
17552        return (preferred == null || preferred.activityInfo == null)
17553                ? null
17554                : new ComponentName(preferred.activityInfo.packageName,
17555                        preferred.activityInfo.name);
17556    }
17557
17558    @Override
17559    public void setHomeActivity(ComponentName comp, int userId) {
17560        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17561        getHomeActivitiesAsUser(homeActivities, userId);
17562
17563        boolean found = false;
17564
17565        final int size = homeActivities.size();
17566        final ComponentName[] set = new ComponentName[size];
17567        for (int i = 0; i < size; i++) {
17568            final ResolveInfo candidate = homeActivities.get(i);
17569            final ActivityInfo info = candidate.activityInfo;
17570            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17571            set[i] = activityName;
17572            if (!found && activityName.equals(comp)) {
17573                found = true;
17574            }
17575        }
17576        if (!found) {
17577            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17578                    + userId);
17579        }
17580        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17581                set, comp, userId);
17582    }
17583
17584    private @Nullable String getSetupWizardPackageName() {
17585        final Intent intent = new Intent(Intent.ACTION_MAIN);
17586        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17587
17588        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17589                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17590                        | MATCH_DISABLED_COMPONENTS,
17591                UserHandle.myUserId());
17592        if (matches.size() == 1) {
17593            return matches.get(0).getComponentInfo().packageName;
17594        } else {
17595            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17596                    + ": matches=" + matches);
17597            return null;
17598        }
17599    }
17600
17601    @Override
17602    public void setApplicationEnabledSetting(String appPackageName,
17603            int newState, int flags, int userId, String callingPackage) {
17604        if (!sUserManager.exists(userId)) return;
17605        if (callingPackage == null) {
17606            callingPackage = Integer.toString(Binder.getCallingUid());
17607        }
17608        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17609    }
17610
17611    @Override
17612    public void setComponentEnabledSetting(ComponentName componentName,
17613            int newState, int flags, int userId) {
17614        if (!sUserManager.exists(userId)) return;
17615        setEnabledSetting(componentName.getPackageName(),
17616                componentName.getClassName(), newState, flags, userId, null);
17617    }
17618
17619    private void setEnabledSetting(final String packageName, String className, int newState,
17620            final int flags, int userId, String callingPackage) {
17621        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17622              || newState == COMPONENT_ENABLED_STATE_ENABLED
17623              || newState == COMPONENT_ENABLED_STATE_DISABLED
17624              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17625              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17626            throw new IllegalArgumentException("Invalid new component state: "
17627                    + newState);
17628        }
17629        PackageSetting pkgSetting;
17630        final int uid = Binder.getCallingUid();
17631        final int permission;
17632        if (uid == Process.SYSTEM_UID) {
17633            permission = PackageManager.PERMISSION_GRANTED;
17634        } else {
17635            permission = mContext.checkCallingOrSelfPermission(
17636                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17637        }
17638        enforceCrossUserPermission(uid, userId,
17639                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17640        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17641        boolean sendNow = false;
17642        boolean isApp = (className == null);
17643        String componentName = isApp ? packageName : className;
17644        int packageUid = -1;
17645        ArrayList<String> components;
17646
17647        // writer
17648        synchronized (mPackages) {
17649            pkgSetting = mSettings.mPackages.get(packageName);
17650            if (pkgSetting == null) {
17651                if (className == null) {
17652                    throw new IllegalArgumentException("Unknown package: " + packageName);
17653                }
17654                throw new IllegalArgumentException(
17655                        "Unknown component: " + packageName + "/" + className);
17656            }
17657        }
17658
17659        // Limit who can change which apps
17660        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17661            // Don't allow apps that don't have permission to modify other apps
17662            if (!allowedByPermission) {
17663                throw new SecurityException(
17664                        "Permission Denial: attempt to change component state from pid="
17665                        + Binder.getCallingPid()
17666                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17667            }
17668            // Don't allow changing protected packages.
17669            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17670                throw new SecurityException("Cannot disable a protected package: " + packageName);
17671            }
17672        }
17673
17674        synchronized (mPackages) {
17675            if (uid == Process.SHELL_UID) {
17676                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17677                int oldState = pkgSetting.getEnabled(userId);
17678                if (className == null
17679                    &&
17680                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17681                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17682                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17683                    &&
17684                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17685                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17686                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17687                    // ok
17688                } else {
17689                    throw new SecurityException(
17690                            "Shell cannot change component state for " + packageName + "/"
17691                            + className + " to " + newState);
17692                }
17693            }
17694            if (className == null) {
17695                // We're dealing with an application/package level state change
17696                if (pkgSetting.getEnabled(userId) == newState) {
17697                    // Nothing to do
17698                    return;
17699                }
17700                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17701                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17702                    // Don't care about who enables an app.
17703                    callingPackage = null;
17704                }
17705                pkgSetting.setEnabled(newState, userId, callingPackage);
17706                // pkgSetting.pkg.mSetEnabled = newState;
17707            } else {
17708                // We're dealing with a component level state change
17709                // First, verify that this is a valid class name.
17710                PackageParser.Package pkg = pkgSetting.pkg;
17711                if (pkg == null || !pkg.hasComponentClassName(className)) {
17712                    if (pkg != null &&
17713                            pkg.applicationInfo.targetSdkVersion >=
17714                                    Build.VERSION_CODES.JELLY_BEAN) {
17715                        throw new IllegalArgumentException("Component class " + className
17716                                + " does not exist in " + packageName);
17717                    } else {
17718                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17719                                + className + " does not exist in " + packageName);
17720                    }
17721                }
17722                switch (newState) {
17723                case COMPONENT_ENABLED_STATE_ENABLED:
17724                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17725                        return;
17726                    }
17727                    break;
17728                case COMPONENT_ENABLED_STATE_DISABLED:
17729                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17730                        return;
17731                    }
17732                    break;
17733                case COMPONENT_ENABLED_STATE_DEFAULT:
17734                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17735                        return;
17736                    }
17737                    break;
17738                default:
17739                    Slog.e(TAG, "Invalid new component state: " + newState);
17740                    return;
17741                }
17742            }
17743            scheduleWritePackageRestrictionsLocked(userId);
17744            components = mPendingBroadcasts.get(userId, packageName);
17745            final boolean newPackage = components == null;
17746            if (newPackage) {
17747                components = new ArrayList<String>();
17748            }
17749            if (!components.contains(componentName)) {
17750                components.add(componentName);
17751            }
17752            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17753                sendNow = true;
17754                // Purge entry from pending broadcast list if another one exists already
17755                // since we are sending one right away.
17756                mPendingBroadcasts.remove(userId, packageName);
17757            } else {
17758                if (newPackage) {
17759                    mPendingBroadcasts.put(userId, packageName, components);
17760                }
17761                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17762                    // Schedule a message
17763                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17764                }
17765            }
17766        }
17767
17768        long callingId = Binder.clearCallingIdentity();
17769        try {
17770            if (sendNow) {
17771                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17772                sendPackageChangedBroadcast(packageName,
17773                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17774            }
17775        } finally {
17776            Binder.restoreCallingIdentity(callingId);
17777        }
17778    }
17779
17780    @Override
17781    public void flushPackageRestrictionsAsUser(int userId) {
17782        if (!sUserManager.exists(userId)) {
17783            return;
17784        }
17785        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17786                false /* checkShell */, "flushPackageRestrictions");
17787        synchronized (mPackages) {
17788            mSettings.writePackageRestrictionsLPr(userId);
17789            mDirtyUsers.remove(userId);
17790            if (mDirtyUsers.isEmpty()) {
17791                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17792            }
17793        }
17794    }
17795
17796    private void sendPackageChangedBroadcast(String packageName,
17797            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17798        if (DEBUG_INSTALL)
17799            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17800                    + componentNames);
17801        Bundle extras = new Bundle(4);
17802        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17803        String nameList[] = new String[componentNames.size()];
17804        componentNames.toArray(nameList);
17805        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17806        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17807        extras.putInt(Intent.EXTRA_UID, packageUid);
17808        // If this is not reporting a change of the overall package, then only send it
17809        // to registered receivers.  We don't want to launch a swath of apps for every
17810        // little component state change.
17811        final int flags = !componentNames.contains(packageName)
17812                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17813        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17814                new int[] {UserHandle.getUserId(packageUid)});
17815    }
17816
17817    @Override
17818    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17819        if (!sUserManager.exists(userId)) return;
17820        final int uid = Binder.getCallingUid();
17821        final int permission = mContext.checkCallingOrSelfPermission(
17822                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17823        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17824        enforceCrossUserPermission(uid, userId,
17825                true /* requireFullPermission */, true /* checkShell */, "stop package");
17826        // writer
17827        synchronized (mPackages) {
17828            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17829                    allowedByPermission, uid, userId)) {
17830                scheduleWritePackageRestrictionsLocked(userId);
17831            }
17832        }
17833    }
17834
17835    @Override
17836    public String getInstallerPackageName(String packageName) {
17837        // reader
17838        synchronized (mPackages) {
17839            return mSettings.getInstallerPackageNameLPr(packageName);
17840        }
17841    }
17842
17843    public boolean isOrphaned(String packageName) {
17844        // reader
17845        synchronized (mPackages) {
17846            return mSettings.isOrphaned(packageName);
17847        }
17848    }
17849
17850    @Override
17851    public int getApplicationEnabledSetting(String packageName, 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 enabled");
17856        // reader
17857        synchronized (mPackages) {
17858            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17859        }
17860    }
17861
17862    @Override
17863    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17864        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17865        int uid = Binder.getCallingUid();
17866        enforceCrossUserPermission(uid, userId,
17867                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17868        // reader
17869        synchronized (mPackages) {
17870            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17871        }
17872    }
17873
17874    @Override
17875    public void enterSafeMode() {
17876        enforceSystemOrRoot("Only the system can request entering safe mode");
17877
17878        if (!mSystemReady) {
17879            mSafeMode = true;
17880        }
17881    }
17882
17883    @Override
17884    public void systemReady() {
17885        mSystemReady = true;
17886
17887        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
17888        // disabled after already being started.
17889        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
17890                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
17891
17892        // Read the compatibilty setting when the system is ready.
17893        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17894                mContext.getContentResolver(),
17895                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17896        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17897        if (DEBUG_SETTINGS) {
17898            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17899        }
17900
17901        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17902
17903        synchronized (mPackages) {
17904            // Verify that all of the preferred activity components actually
17905            // exist.  It is possible for applications to be updated and at
17906            // that point remove a previously declared activity component that
17907            // had been set as a preferred activity.  We try to clean this up
17908            // the next time we encounter that preferred activity, but it is
17909            // possible for the user flow to never be able to return to that
17910            // situation so here we do a sanity check to make sure we haven't
17911            // left any junk around.
17912            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17913            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17914                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17915                removed.clear();
17916                for (PreferredActivity pa : pir.filterSet()) {
17917                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17918                        removed.add(pa);
17919                    }
17920                }
17921                if (removed.size() > 0) {
17922                    for (int r=0; r<removed.size(); r++) {
17923                        PreferredActivity pa = removed.get(r);
17924                        Slog.w(TAG, "Removing dangling preferred activity: "
17925                                + pa.mPref.mComponent);
17926                        pir.removeFilter(pa);
17927                    }
17928                    mSettings.writePackageRestrictionsLPr(
17929                            mSettings.mPreferredActivities.keyAt(i));
17930                }
17931            }
17932
17933            for (int userId : UserManagerService.getInstance().getUserIds()) {
17934                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17935                    grantPermissionsUserIds = ArrayUtils.appendInt(
17936                            grantPermissionsUserIds, userId);
17937                }
17938            }
17939        }
17940        sUserManager.systemReady();
17941
17942        // If we upgraded grant all default permissions before kicking off.
17943        for (int userId : grantPermissionsUserIds) {
17944            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17945        }
17946
17947        // Kick off any messages waiting for system ready
17948        if (mPostSystemReadyMessages != null) {
17949            for (Message msg : mPostSystemReadyMessages) {
17950                msg.sendToTarget();
17951            }
17952            mPostSystemReadyMessages = null;
17953        }
17954
17955        // Watch for external volumes that come and go over time
17956        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17957        storage.registerListener(mStorageListener);
17958
17959        mInstallerService.systemReady();
17960        mPackageDexOptimizer.systemReady();
17961
17962        MountServiceInternal mountServiceInternal = LocalServices.getService(
17963                MountServiceInternal.class);
17964        mountServiceInternal.addExternalStoragePolicy(
17965                new MountServiceInternal.ExternalStorageMountPolicy() {
17966            @Override
17967            public int getMountMode(int uid, String packageName) {
17968                if (Process.isIsolated(uid)) {
17969                    return Zygote.MOUNT_EXTERNAL_NONE;
17970                }
17971                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17972                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17973                }
17974                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17975                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17976                }
17977                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17978                    return Zygote.MOUNT_EXTERNAL_READ;
17979                }
17980                return Zygote.MOUNT_EXTERNAL_WRITE;
17981            }
17982
17983            @Override
17984            public boolean hasExternalStorage(int uid, String packageName) {
17985                return true;
17986            }
17987        });
17988
17989        // Now that we're mostly running, clean up stale users and apps
17990        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
17991        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
17992    }
17993
17994    @Override
17995    public boolean isSafeMode() {
17996        return mSafeMode;
17997    }
17998
17999    @Override
18000    public boolean hasSystemUidErrors() {
18001        return mHasSystemUidErrors;
18002    }
18003
18004    static String arrayToString(int[] array) {
18005        StringBuffer buf = new StringBuffer(128);
18006        buf.append('[');
18007        if (array != null) {
18008            for (int i=0; i<array.length; i++) {
18009                if (i > 0) buf.append(", ");
18010                buf.append(array[i]);
18011            }
18012        }
18013        buf.append(']');
18014        return buf.toString();
18015    }
18016
18017    static class DumpState {
18018        public static final int DUMP_LIBS = 1 << 0;
18019        public static final int DUMP_FEATURES = 1 << 1;
18020        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18021        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18022        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18023        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18024        public static final int DUMP_PERMISSIONS = 1 << 6;
18025        public static final int DUMP_PACKAGES = 1 << 7;
18026        public static final int DUMP_SHARED_USERS = 1 << 8;
18027        public static final int DUMP_MESSAGES = 1 << 9;
18028        public static final int DUMP_PROVIDERS = 1 << 10;
18029        public static final int DUMP_VERIFIERS = 1 << 11;
18030        public static final int DUMP_PREFERRED = 1 << 12;
18031        public static final int DUMP_PREFERRED_XML = 1 << 13;
18032        public static final int DUMP_KEYSETS = 1 << 14;
18033        public static final int DUMP_VERSION = 1 << 15;
18034        public static final int DUMP_INSTALLS = 1 << 16;
18035        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18036        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18037        public static final int DUMP_FROZEN = 1 << 19;
18038        public static final int DUMP_DEXOPT = 1 << 20;
18039        public static final int DUMP_COMPILER_STATS = 1 << 21;
18040
18041        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18042
18043        private int mTypes;
18044
18045        private int mOptions;
18046
18047        private boolean mTitlePrinted;
18048
18049        private SharedUserSetting mSharedUser;
18050
18051        public boolean isDumping(int type) {
18052            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18053                return true;
18054            }
18055
18056            return (mTypes & type) != 0;
18057        }
18058
18059        public void setDump(int type) {
18060            mTypes |= type;
18061        }
18062
18063        public boolean isOptionEnabled(int option) {
18064            return (mOptions & option) != 0;
18065        }
18066
18067        public void setOptionEnabled(int option) {
18068            mOptions |= option;
18069        }
18070
18071        public boolean onTitlePrinted() {
18072            final boolean printed = mTitlePrinted;
18073            mTitlePrinted = true;
18074            return printed;
18075        }
18076
18077        public boolean getTitlePrinted() {
18078            return mTitlePrinted;
18079        }
18080
18081        public void setTitlePrinted(boolean enabled) {
18082            mTitlePrinted = enabled;
18083        }
18084
18085        public SharedUserSetting getSharedUser() {
18086            return mSharedUser;
18087        }
18088
18089        public void setSharedUser(SharedUserSetting user) {
18090            mSharedUser = user;
18091        }
18092    }
18093
18094    @Override
18095    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18096            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18097        (new PackageManagerShellCommand(this)).exec(
18098                this, in, out, err, args, resultReceiver);
18099    }
18100
18101    @Override
18102    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18103        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18104                != PackageManager.PERMISSION_GRANTED) {
18105            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18106                    + Binder.getCallingPid()
18107                    + ", uid=" + Binder.getCallingUid()
18108                    + " without permission "
18109                    + android.Manifest.permission.DUMP);
18110            return;
18111        }
18112
18113        DumpState dumpState = new DumpState();
18114        boolean fullPreferred = false;
18115        boolean checkin = false;
18116
18117        String packageName = null;
18118        ArraySet<String> permissionNames = null;
18119
18120        int opti = 0;
18121        while (opti < args.length) {
18122            String opt = args[opti];
18123            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18124                break;
18125            }
18126            opti++;
18127
18128            if ("-a".equals(opt)) {
18129                // Right now we only know how to print all.
18130            } else if ("-h".equals(opt)) {
18131                pw.println("Package manager dump options:");
18132                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18133                pw.println("    --checkin: dump for a checkin");
18134                pw.println("    -f: print details of intent filters");
18135                pw.println("    -h: print this help");
18136                pw.println("  cmd may be one of:");
18137                pw.println("    l[ibraries]: list known shared libraries");
18138                pw.println("    f[eatures]: list device features");
18139                pw.println("    k[eysets]: print known keysets");
18140                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18141                pw.println("    perm[issions]: dump permissions");
18142                pw.println("    permission [name ...]: dump declaration and use of given permission");
18143                pw.println("    pref[erred]: print preferred package settings");
18144                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18145                pw.println("    prov[iders]: dump content providers");
18146                pw.println("    p[ackages]: dump installed packages");
18147                pw.println("    s[hared-users]: dump shared user IDs");
18148                pw.println("    m[essages]: print collected runtime messages");
18149                pw.println("    v[erifiers]: print package verifier info");
18150                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18151                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18152                pw.println("    version: print database version info");
18153                pw.println("    write: write current settings now");
18154                pw.println("    installs: details about install sessions");
18155                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18156                pw.println("    dexopt: dump dexopt state");
18157                pw.println("    compiler-stats: dump compiler statistics");
18158                pw.println("    <package.name>: info about given package");
18159                return;
18160            } else if ("--checkin".equals(opt)) {
18161                checkin = true;
18162            } else if ("-f".equals(opt)) {
18163                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18164            } else {
18165                pw.println("Unknown argument: " + opt + "; use -h for help");
18166            }
18167        }
18168
18169        // Is the caller requesting to dump a particular piece of data?
18170        if (opti < args.length) {
18171            String cmd = args[opti];
18172            opti++;
18173            // Is this a package name?
18174            if ("android".equals(cmd) || cmd.contains(".")) {
18175                packageName = cmd;
18176                // When dumping a single package, we always dump all of its
18177                // filter information since the amount of data will be reasonable.
18178                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18179            } else if ("check-permission".equals(cmd)) {
18180                if (opti >= args.length) {
18181                    pw.println("Error: check-permission missing permission argument");
18182                    return;
18183                }
18184                String perm = args[opti];
18185                opti++;
18186                if (opti >= args.length) {
18187                    pw.println("Error: check-permission missing package argument");
18188                    return;
18189                }
18190                String pkg = args[opti];
18191                opti++;
18192                int user = UserHandle.getUserId(Binder.getCallingUid());
18193                if (opti < args.length) {
18194                    try {
18195                        user = Integer.parseInt(args[opti]);
18196                    } catch (NumberFormatException e) {
18197                        pw.println("Error: check-permission user argument is not a number: "
18198                                + args[opti]);
18199                        return;
18200                    }
18201                }
18202                pw.println(checkPermission(perm, pkg, user));
18203                return;
18204            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18205                dumpState.setDump(DumpState.DUMP_LIBS);
18206            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18207                dumpState.setDump(DumpState.DUMP_FEATURES);
18208            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18209                if (opti >= args.length) {
18210                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18211                            | DumpState.DUMP_SERVICE_RESOLVERS
18212                            | DumpState.DUMP_RECEIVER_RESOLVERS
18213                            | DumpState.DUMP_CONTENT_RESOLVERS);
18214                } else {
18215                    while (opti < args.length) {
18216                        String name = args[opti];
18217                        if ("a".equals(name) || "activity".equals(name)) {
18218                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18219                        } else if ("s".equals(name) || "service".equals(name)) {
18220                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18221                        } else if ("r".equals(name) || "receiver".equals(name)) {
18222                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18223                        } else if ("c".equals(name) || "content".equals(name)) {
18224                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18225                        } else {
18226                            pw.println("Error: unknown resolver table type: " + name);
18227                            return;
18228                        }
18229                        opti++;
18230                    }
18231                }
18232            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18233                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18234            } else if ("permission".equals(cmd)) {
18235                if (opti >= args.length) {
18236                    pw.println("Error: permission requires permission name");
18237                    return;
18238                }
18239                permissionNames = new ArraySet<>();
18240                while (opti < args.length) {
18241                    permissionNames.add(args[opti]);
18242                    opti++;
18243                }
18244                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18245                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18246            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18247                dumpState.setDump(DumpState.DUMP_PREFERRED);
18248            } else if ("preferred-xml".equals(cmd)) {
18249                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18250                if (opti < args.length && "--full".equals(args[opti])) {
18251                    fullPreferred = true;
18252                    opti++;
18253                }
18254            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18255                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18256            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18257                dumpState.setDump(DumpState.DUMP_PACKAGES);
18258            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18259                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18260            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18261                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18262            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18263                dumpState.setDump(DumpState.DUMP_MESSAGES);
18264            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18265                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18266            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18267                    || "intent-filter-verifiers".equals(cmd)) {
18268                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18269            } else if ("version".equals(cmd)) {
18270                dumpState.setDump(DumpState.DUMP_VERSION);
18271            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18272                dumpState.setDump(DumpState.DUMP_KEYSETS);
18273            } else if ("installs".equals(cmd)) {
18274                dumpState.setDump(DumpState.DUMP_INSTALLS);
18275            } else if ("frozen".equals(cmd)) {
18276                dumpState.setDump(DumpState.DUMP_FROZEN);
18277            } else if ("dexopt".equals(cmd)) {
18278                dumpState.setDump(DumpState.DUMP_DEXOPT);
18279            } else if ("compiler-stats".equals(cmd)) {
18280                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18281            } else if ("write".equals(cmd)) {
18282                synchronized (mPackages) {
18283                    mSettings.writeLPr();
18284                    pw.println("Settings written.");
18285                    return;
18286                }
18287            }
18288        }
18289
18290        if (checkin) {
18291            pw.println("vers,1");
18292        }
18293
18294        // reader
18295        synchronized (mPackages) {
18296            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18297                if (!checkin) {
18298                    if (dumpState.onTitlePrinted())
18299                        pw.println();
18300                    pw.println("Database versions:");
18301                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18302                }
18303            }
18304
18305            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18306                if (!checkin) {
18307                    if (dumpState.onTitlePrinted())
18308                        pw.println();
18309                    pw.println("Verifiers:");
18310                    pw.print("  Required: ");
18311                    pw.print(mRequiredVerifierPackage);
18312                    pw.print(" (uid=");
18313                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18314                            UserHandle.USER_SYSTEM));
18315                    pw.println(")");
18316                } else if (mRequiredVerifierPackage != null) {
18317                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18318                    pw.print(",");
18319                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18320                            UserHandle.USER_SYSTEM));
18321                }
18322            }
18323
18324            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18325                    packageName == null) {
18326                if (mIntentFilterVerifierComponent != null) {
18327                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18328                    if (!checkin) {
18329                        if (dumpState.onTitlePrinted())
18330                            pw.println();
18331                        pw.println("Intent Filter Verifier:");
18332                        pw.print("  Using: ");
18333                        pw.print(verifierPackageName);
18334                        pw.print(" (uid=");
18335                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18336                                UserHandle.USER_SYSTEM));
18337                        pw.println(")");
18338                    } else if (verifierPackageName != null) {
18339                        pw.print("ifv,"); pw.print(verifierPackageName);
18340                        pw.print(",");
18341                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18342                                UserHandle.USER_SYSTEM));
18343                    }
18344                } else {
18345                    pw.println();
18346                    pw.println("No Intent Filter Verifier available!");
18347                }
18348            }
18349
18350            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18351                boolean printedHeader = false;
18352                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18353                while (it.hasNext()) {
18354                    String name = it.next();
18355                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18356                    if (!checkin) {
18357                        if (!printedHeader) {
18358                            if (dumpState.onTitlePrinted())
18359                                pw.println();
18360                            pw.println("Libraries:");
18361                            printedHeader = true;
18362                        }
18363                        pw.print("  ");
18364                    } else {
18365                        pw.print("lib,");
18366                    }
18367                    pw.print(name);
18368                    if (!checkin) {
18369                        pw.print(" -> ");
18370                    }
18371                    if (ent.path != null) {
18372                        if (!checkin) {
18373                            pw.print("(jar) ");
18374                            pw.print(ent.path);
18375                        } else {
18376                            pw.print(",jar,");
18377                            pw.print(ent.path);
18378                        }
18379                    } else {
18380                        if (!checkin) {
18381                            pw.print("(apk) ");
18382                            pw.print(ent.apk);
18383                        } else {
18384                            pw.print(",apk,");
18385                            pw.print(ent.apk);
18386                        }
18387                    }
18388                    pw.println();
18389                }
18390            }
18391
18392            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18393                if (dumpState.onTitlePrinted())
18394                    pw.println();
18395                if (!checkin) {
18396                    pw.println("Features:");
18397                }
18398
18399                for (FeatureInfo feat : mAvailableFeatures.values()) {
18400                    if (checkin) {
18401                        pw.print("feat,");
18402                        pw.print(feat.name);
18403                        pw.print(",");
18404                        pw.println(feat.version);
18405                    } else {
18406                        pw.print("  ");
18407                        pw.print(feat.name);
18408                        if (feat.version > 0) {
18409                            pw.print(" version=");
18410                            pw.print(feat.version);
18411                        }
18412                        pw.println();
18413                    }
18414                }
18415            }
18416
18417            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18418                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18419                        : "Activity Resolver Table:", "  ", packageName,
18420                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18421                    dumpState.setTitlePrinted(true);
18422                }
18423            }
18424            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18425                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18426                        : "Receiver Resolver Table:", "  ", packageName,
18427                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18428                    dumpState.setTitlePrinted(true);
18429                }
18430            }
18431            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18432                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18433                        : "Service Resolver Table:", "  ", packageName,
18434                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18435                    dumpState.setTitlePrinted(true);
18436                }
18437            }
18438            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18439                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18440                        : "Provider Resolver Table:", "  ", packageName,
18441                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18442                    dumpState.setTitlePrinted(true);
18443                }
18444            }
18445
18446            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18447                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18448                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18449                    int user = mSettings.mPreferredActivities.keyAt(i);
18450                    if (pir.dump(pw,
18451                            dumpState.getTitlePrinted()
18452                                ? "\nPreferred Activities User " + user + ":"
18453                                : "Preferred Activities User " + user + ":", "  ",
18454                            packageName, true, false)) {
18455                        dumpState.setTitlePrinted(true);
18456                    }
18457                }
18458            }
18459
18460            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18461                pw.flush();
18462                FileOutputStream fout = new FileOutputStream(fd);
18463                BufferedOutputStream str = new BufferedOutputStream(fout);
18464                XmlSerializer serializer = new FastXmlSerializer();
18465                try {
18466                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18467                    serializer.startDocument(null, true);
18468                    serializer.setFeature(
18469                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18470                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18471                    serializer.endDocument();
18472                    serializer.flush();
18473                } catch (IllegalArgumentException e) {
18474                    pw.println("Failed writing: " + e);
18475                } catch (IllegalStateException e) {
18476                    pw.println("Failed writing: " + e);
18477                } catch (IOException e) {
18478                    pw.println("Failed writing: " + e);
18479                }
18480            }
18481
18482            if (!checkin
18483                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18484                    && packageName == null) {
18485                pw.println();
18486                int count = mSettings.mPackages.size();
18487                if (count == 0) {
18488                    pw.println("No applications!");
18489                    pw.println();
18490                } else {
18491                    final String prefix = "  ";
18492                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18493                    if (allPackageSettings.size() == 0) {
18494                        pw.println("No domain preferred apps!");
18495                        pw.println();
18496                    } else {
18497                        pw.println("App verification status:");
18498                        pw.println();
18499                        count = 0;
18500                        for (PackageSetting ps : allPackageSettings) {
18501                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18502                            if (ivi == null || ivi.getPackageName() == null) continue;
18503                            pw.println(prefix + "Package: " + ivi.getPackageName());
18504                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18505                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18506                            pw.println();
18507                            count++;
18508                        }
18509                        if (count == 0) {
18510                            pw.println(prefix + "No app verification established.");
18511                            pw.println();
18512                        }
18513                        for (int userId : sUserManager.getUserIds()) {
18514                            pw.println("App linkages for user " + userId + ":");
18515                            pw.println();
18516                            count = 0;
18517                            for (PackageSetting ps : allPackageSettings) {
18518                                final long status = ps.getDomainVerificationStatusForUser(userId);
18519                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18520                                    continue;
18521                                }
18522                                pw.println(prefix + "Package: " + ps.name);
18523                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18524                                String statusStr = IntentFilterVerificationInfo.
18525                                        getStatusStringFromValue(status);
18526                                pw.println(prefix + "Status:  " + statusStr);
18527                                pw.println();
18528                                count++;
18529                            }
18530                            if (count == 0) {
18531                                pw.println(prefix + "No configured app linkages.");
18532                                pw.println();
18533                            }
18534                        }
18535                    }
18536                }
18537            }
18538
18539            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18540                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18541                if (packageName == null && permissionNames == null) {
18542                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18543                        if (iperm == 0) {
18544                            if (dumpState.onTitlePrinted())
18545                                pw.println();
18546                            pw.println("AppOp Permissions:");
18547                        }
18548                        pw.print("  AppOp Permission ");
18549                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18550                        pw.println(":");
18551                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18552                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18553                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18554                        }
18555                    }
18556                }
18557            }
18558
18559            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18560                boolean printedSomething = false;
18561                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18562                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18563                        continue;
18564                    }
18565                    if (!printedSomething) {
18566                        if (dumpState.onTitlePrinted())
18567                            pw.println();
18568                        pw.println("Registered ContentProviders:");
18569                        printedSomething = true;
18570                    }
18571                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18572                    pw.print("    "); pw.println(p.toString());
18573                }
18574                printedSomething = false;
18575                for (Map.Entry<String, PackageParser.Provider> entry :
18576                        mProvidersByAuthority.entrySet()) {
18577                    PackageParser.Provider p = entry.getValue();
18578                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18579                        continue;
18580                    }
18581                    if (!printedSomething) {
18582                        if (dumpState.onTitlePrinted())
18583                            pw.println();
18584                        pw.println("ContentProvider Authorities:");
18585                        printedSomething = true;
18586                    }
18587                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18588                    pw.print("    "); pw.println(p.toString());
18589                    if (p.info != null && p.info.applicationInfo != null) {
18590                        final String appInfo = p.info.applicationInfo.toString();
18591                        pw.print("      applicationInfo="); pw.println(appInfo);
18592                    }
18593                }
18594            }
18595
18596            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18597                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18598            }
18599
18600            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18601                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18602            }
18603
18604            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18605                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18606            }
18607
18608            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18609                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18610            }
18611
18612            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18613                // XXX should handle packageName != null by dumping only install data that
18614                // the given package is involved with.
18615                if (dumpState.onTitlePrinted()) pw.println();
18616                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18617            }
18618
18619            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18620                // XXX should handle packageName != null by dumping only install data that
18621                // the given package is involved with.
18622                if (dumpState.onTitlePrinted()) pw.println();
18623
18624                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18625                ipw.println();
18626                ipw.println("Frozen packages:");
18627                ipw.increaseIndent();
18628                if (mFrozenPackages.size() == 0) {
18629                    ipw.println("(none)");
18630                } else {
18631                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18632                        ipw.println(mFrozenPackages.valueAt(i));
18633                    }
18634                }
18635                ipw.decreaseIndent();
18636            }
18637
18638            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18639                if (dumpState.onTitlePrinted()) pw.println();
18640                dumpDexoptStateLPr(pw, packageName);
18641            }
18642
18643            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
18644                if (dumpState.onTitlePrinted()) pw.println();
18645                dumpCompilerStatsLPr(pw, packageName);
18646            }
18647
18648            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18649                if (dumpState.onTitlePrinted()) pw.println();
18650                mSettings.dumpReadMessagesLPr(pw, dumpState);
18651
18652                pw.println();
18653                pw.println("Package warning messages:");
18654                BufferedReader in = null;
18655                String line = null;
18656                try {
18657                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18658                    while ((line = in.readLine()) != null) {
18659                        if (line.contains("ignored: updated version")) continue;
18660                        pw.println(line);
18661                    }
18662                } catch (IOException ignored) {
18663                } finally {
18664                    IoUtils.closeQuietly(in);
18665                }
18666            }
18667
18668            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18669                BufferedReader in = null;
18670                String line = null;
18671                try {
18672                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18673                    while ((line = in.readLine()) != null) {
18674                        if (line.contains("ignored: updated version")) continue;
18675                        pw.print("msg,");
18676                        pw.println(line);
18677                    }
18678                } catch (IOException ignored) {
18679                } finally {
18680                    IoUtils.closeQuietly(in);
18681                }
18682            }
18683        }
18684    }
18685
18686    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18687        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18688        ipw.println();
18689        ipw.println("Dexopt state:");
18690        ipw.increaseIndent();
18691        Collection<PackageParser.Package> packages = null;
18692        if (packageName != null) {
18693            PackageParser.Package targetPackage = mPackages.get(packageName);
18694            if (targetPackage != null) {
18695                packages = Collections.singletonList(targetPackage);
18696            } else {
18697                ipw.println("Unable to find package: " + packageName);
18698                return;
18699            }
18700        } else {
18701            packages = mPackages.values();
18702        }
18703
18704        for (PackageParser.Package pkg : packages) {
18705            ipw.println("[" + pkg.packageName + "]");
18706            ipw.increaseIndent();
18707            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18708            ipw.decreaseIndent();
18709        }
18710    }
18711
18712    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
18713        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18714        ipw.println();
18715        ipw.println("Compiler stats:");
18716        ipw.increaseIndent();
18717        Collection<PackageParser.Package> packages = null;
18718        if (packageName != null) {
18719            PackageParser.Package targetPackage = mPackages.get(packageName);
18720            if (targetPackage != null) {
18721                packages = Collections.singletonList(targetPackage);
18722            } else {
18723                ipw.println("Unable to find package: " + packageName);
18724                return;
18725            }
18726        } else {
18727            packages = mPackages.values();
18728        }
18729
18730        for (PackageParser.Package pkg : packages) {
18731            ipw.println("[" + pkg.packageName + "]");
18732            ipw.increaseIndent();
18733
18734            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
18735            if (stats == null) {
18736                ipw.println("(No recorded stats)");
18737            } else {
18738                stats.dump(ipw);
18739            }
18740            ipw.decreaseIndent();
18741        }
18742    }
18743
18744    private String dumpDomainString(String packageName) {
18745        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18746                .getList();
18747        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18748
18749        ArraySet<String> result = new ArraySet<>();
18750        if (iviList.size() > 0) {
18751            for (IntentFilterVerificationInfo ivi : iviList) {
18752                for (String host : ivi.getDomains()) {
18753                    result.add(host);
18754                }
18755            }
18756        }
18757        if (filters != null && filters.size() > 0) {
18758            for (IntentFilter filter : filters) {
18759                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18760                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18761                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18762                    result.addAll(filter.getHostsList());
18763                }
18764            }
18765        }
18766
18767        StringBuilder sb = new StringBuilder(result.size() * 16);
18768        for (String domain : result) {
18769            if (sb.length() > 0) sb.append(" ");
18770            sb.append(domain);
18771        }
18772        return sb.toString();
18773    }
18774
18775    // ------- apps on sdcard specific code -------
18776    static final boolean DEBUG_SD_INSTALL = false;
18777
18778    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18779
18780    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18781
18782    private boolean mMediaMounted = false;
18783
18784    static String getEncryptKey() {
18785        try {
18786            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18787                    SD_ENCRYPTION_KEYSTORE_NAME);
18788            if (sdEncKey == null) {
18789                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18790                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18791                if (sdEncKey == null) {
18792                    Slog.e(TAG, "Failed to create encryption keys");
18793                    return null;
18794                }
18795            }
18796            return sdEncKey;
18797        } catch (NoSuchAlgorithmException nsae) {
18798            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18799            return null;
18800        } catch (IOException ioe) {
18801            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18802            return null;
18803        }
18804    }
18805
18806    /*
18807     * Update media status on PackageManager.
18808     */
18809    @Override
18810    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18811        int callingUid = Binder.getCallingUid();
18812        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18813            throw new SecurityException("Media status can only be updated by the system");
18814        }
18815        // reader; this apparently protects mMediaMounted, but should probably
18816        // be a different lock in that case.
18817        synchronized (mPackages) {
18818            Log.i(TAG, "Updating external media status from "
18819                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18820                    + (mediaStatus ? "mounted" : "unmounted"));
18821            if (DEBUG_SD_INSTALL)
18822                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18823                        + ", mMediaMounted=" + mMediaMounted);
18824            if (mediaStatus == mMediaMounted) {
18825                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18826                        : 0, -1);
18827                mHandler.sendMessage(msg);
18828                return;
18829            }
18830            mMediaMounted = mediaStatus;
18831        }
18832        // Queue up an async operation since the package installation may take a
18833        // little while.
18834        mHandler.post(new Runnable() {
18835            public void run() {
18836                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18837            }
18838        });
18839    }
18840
18841    /**
18842     * Called by MountService when the initial ASECs to scan are available.
18843     * Should block until all the ASEC containers are finished being scanned.
18844     */
18845    public void scanAvailableAsecs() {
18846        updateExternalMediaStatusInner(true, false, false);
18847    }
18848
18849    /*
18850     * Collect information of applications on external media, map them against
18851     * existing containers and update information based on current mount status.
18852     * Please note that we always have to report status if reportStatus has been
18853     * set to true especially when unloading packages.
18854     */
18855    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18856            boolean externalStorage) {
18857        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18858        int[] uidArr = EmptyArray.INT;
18859
18860        final String[] list = PackageHelper.getSecureContainerList();
18861        if (ArrayUtils.isEmpty(list)) {
18862            Log.i(TAG, "No secure containers found");
18863        } else {
18864            // Process list of secure containers and categorize them
18865            // as active or stale based on their package internal state.
18866
18867            // reader
18868            synchronized (mPackages) {
18869                for (String cid : list) {
18870                    // Leave stages untouched for now; installer service owns them
18871                    if (PackageInstallerService.isStageName(cid)) continue;
18872
18873                    if (DEBUG_SD_INSTALL)
18874                        Log.i(TAG, "Processing container " + cid);
18875                    String pkgName = getAsecPackageName(cid);
18876                    if (pkgName == null) {
18877                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18878                        continue;
18879                    }
18880                    if (DEBUG_SD_INSTALL)
18881                        Log.i(TAG, "Looking for pkg : " + pkgName);
18882
18883                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18884                    if (ps == null) {
18885                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18886                        continue;
18887                    }
18888
18889                    /*
18890                     * Skip packages that are not external if we're unmounting
18891                     * external storage.
18892                     */
18893                    if (externalStorage && !isMounted && !isExternal(ps)) {
18894                        continue;
18895                    }
18896
18897                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18898                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18899                    // The package status is changed only if the code path
18900                    // matches between settings and the container id.
18901                    if (ps.codePathString != null
18902                            && ps.codePathString.startsWith(args.getCodePath())) {
18903                        if (DEBUG_SD_INSTALL) {
18904                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18905                                    + " at code path: " + ps.codePathString);
18906                        }
18907
18908                        // We do have a valid package installed on sdcard
18909                        processCids.put(args, ps.codePathString);
18910                        final int uid = ps.appId;
18911                        if (uid != -1) {
18912                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18913                        }
18914                    } else {
18915                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18916                                + ps.codePathString);
18917                    }
18918                }
18919            }
18920
18921            Arrays.sort(uidArr);
18922        }
18923
18924        // Process packages with valid entries.
18925        if (isMounted) {
18926            if (DEBUG_SD_INSTALL)
18927                Log.i(TAG, "Loading packages");
18928            loadMediaPackages(processCids, uidArr, externalStorage);
18929            startCleaningPackages();
18930            mInstallerService.onSecureContainersAvailable();
18931        } else {
18932            if (DEBUG_SD_INSTALL)
18933                Log.i(TAG, "Unloading packages");
18934            unloadMediaPackages(processCids, uidArr, reportStatus);
18935        }
18936    }
18937
18938    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18939            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18940        final int size = infos.size();
18941        final String[] packageNames = new String[size];
18942        final int[] packageUids = new int[size];
18943        for (int i = 0; i < size; i++) {
18944            final ApplicationInfo info = infos.get(i);
18945            packageNames[i] = info.packageName;
18946            packageUids[i] = info.uid;
18947        }
18948        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18949                finishedReceiver);
18950    }
18951
18952    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18953            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18954        sendResourcesChangedBroadcast(mediaStatus, replacing,
18955                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18956    }
18957
18958    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18959            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18960        int size = pkgList.length;
18961        if (size > 0) {
18962            // Send broadcasts here
18963            Bundle extras = new Bundle();
18964            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18965            if (uidArr != null) {
18966                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18967            }
18968            if (replacing) {
18969                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18970            }
18971            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18972                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18973            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18974        }
18975    }
18976
18977   /*
18978     * Look at potentially valid container ids from processCids If package
18979     * information doesn't match the one on record or package scanning fails,
18980     * the cid is added to list of removeCids. We currently don't delete stale
18981     * containers.
18982     */
18983    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18984            boolean externalStorage) {
18985        ArrayList<String> pkgList = new ArrayList<String>();
18986        Set<AsecInstallArgs> keys = processCids.keySet();
18987
18988        for (AsecInstallArgs args : keys) {
18989            String codePath = processCids.get(args);
18990            if (DEBUG_SD_INSTALL)
18991                Log.i(TAG, "Loading container : " + args.cid);
18992            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18993            try {
18994                // Make sure there are no container errors first.
18995                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18996                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18997                            + " when installing from sdcard");
18998                    continue;
18999                }
19000                // Check code path here.
19001                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19002                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19003                            + " does not match one in settings " + codePath);
19004                    continue;
19005                }
19006                // Parse package
19007                int parseFlags = mDefParseFlags;
19008                if (args.isExternalAsec()) {
19009                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19010                }
19011                if (args.isFwdLocked()) {
19012                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19013                }
19014
19015                synchronized (mInstallLock) {
19016                    PackageParser.Package pkg = null;
19017                    try {
19018                        // Sadly we don't know the package name yet to freeze it
19019                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19020                                SCAN_IGNORE_FROZEN, 0, null);
19021                    } catch (PackageManagerException e) {
19022                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19023                    }
19024                    // Scan the package
19025                    if (pkg != null) {
19026                        /*
19027                         * TODO why is the lock being held? doPostInstall is
19028                         * called in other places without the lock. This needs
19029                         * to be straightened out.
19030                         */
19031                        // writer
19032                        synchronized (mPackages) {
19033                            retCode = PackageManager.INSTALL_SUCCEEDED;
19034                            pkgList.add(pkg.packageName);
19035                            // Post process args
19036                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19037                                    pkg.applicationInfo.uid);
19038                        }
19039                    } else {
19040                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19041                    }
19042                }
19043
19044            } finally {
19045                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19046                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19047                }
19048            }
19049        }
19050        // writer
19051        synchronized (mPackages) {
19052            // If the platform SDK has changed since the last time we booted,
19053            // we need to re-grant app permission to catch any new ones that
19054            // appear. This is really a hack, and means that apps can in some
19055            // cases get permissions that the user didn't initially explicitly
19056            // allow... it would be nice to have some better way to handle
19057            // this situation.
19058            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19059                    : mSettings.getInternalVersion();
19060            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19061                    : StorageManager.UUID_PRIVATE_INTERNAL;
19062
19063            int updateFlags = UPDATE_PERMISSIONS_ALL;
19064            if (ver.sdkVersion != mSdkVersion) {
19065                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19066                        + mSdkVersion + "; regranting permissions for external");
19067                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19068            }
19069            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19070
19071            // Yay, everything is now upgraded
19072            ver.forceCurrent();
19073
19074            // can downgrade to reader
19075            // Persist settings
19076            mSettings.writeLPr();
19077        }
19078        // Send a broadcast to let everyone know we are done processing
19079        if (pkgList.size() > 0) {
19080            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19081        }
19082    }
19083
19084   /*
19085     * Utility method to unload a list of specified containers
19086     */
19087    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19088        // Just unmount all valid containers.
19089        for (AsecInstallArgs arg : cidArgs) {
19090            synchronized (mInstallLock) {
19091                arg.doPostDeleteLI(false);
19092           }
19093       }
19094   }
19095
19096    /*
19097     * Unload packages mounted on external media. This involves deleting package
19098     * data from internal structures, sending broadcasts about disabled packages,
19099     * gc'ing to free up references, unmounting all secure containers
19100     * corresponding to packages on external media, and posting a
19101     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19102     * that we always have to post this message if status has been requested no
19103     * matter what.
19104     */
19105    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19106            final boolean reportStatus) {
19107        if (DEBUG_SD_INSTALL)
19108            Log.i(TAG, "unloading media packages");
19109        ArrayList<String> pkgList = new ArrayList<String>();
19110        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19111        final Set<AsecInstallArgs> keys = processCids.keySet();
19112        for (AsecInstallArgs args : keys) {
19113            String pkgName = args.getPackageName();
19114            if (DEBUG_SD_INSTALL)
19115                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19116            // Delete package internally
19117            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19118            synchronized (mInstallLock) {
19119                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19120                final boolean res;
19121                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19122                        "unloadMediaPackages")) {
19123                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19124                            null);
19125                }
19126                if (res) {
19127                    pkgList.add(pkgName);
19128                } else {
19129                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19130                    failedList.add(args);
19131                }
19132            }
19133        }
19134
19135        // reader
19136        synchronized (mPackages) {
19137            // We didn't update the settings after removing each package;
19138            // write them now for all packages.
19139            mSettings.writeLPr();
19140        }
19141
19142        // We have to absolutely send UPDATED_MEDIA_STATUS only
19143        // after confirming that all the receivers processed the ordered
19144        // broadcast when packages get disabled, force a gc to clean things up.
19145        // and unload all the containers.
19146        if (pkgList.size() > 0) {
19147            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19148                    new IIntentReceiver.Stub() {
19149                public void performReceive(Intent intent, int resultCode, String data,
19150                        Bundle extras, boolean ordered, boolean sticky,
19151                        int sendingUser) throws RemoteException {
19152                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19153                            reportStatus ? 1 : 0, 1, keys);
19154                    mHandler.sendMessage(msg);
19155                }
19156            });
19157        } else {
19158            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19159                    keys);
19160            mHandler.sendMessage(msg);
19161        }
19162    }
19163
19164    private void loadPrivatePackages(final VolumeInfo vol) {
19165        mHandler.post(new Runnable() {
19166            @Override
19167            public void run() {
19168                loadPrivatePackagesInner(vol);
19169            }
19170        });
19171    }
19172
19173    private void loadPrivatePackagesInner(VolumeInfo vol) {
19174        final String volumeUuid = vol.fsUuid;
19175        if (TextUtils.isEmpty(volumeUuid)) {
19176            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19177            return;
19178        }
19179
19180        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19181        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19182        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19183
19184        final VersionInfo ver;
19185        final List<PackageSetting> packages;
19186        synchronized (mPackages) {
19187            ver = mSettings.findOrCreateVersion(volumeUuid);
19188            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19189        }
19190
19191        for (PackageSetting ps : packages) {
19192            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19193            synchronized (mInstallLock) {
19194                final PackageParser.Package pkg;
19195                try {
19196                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19197                    loaded.add(pkg.applicationInfo);
19198
19199                } catch (PackageManagerException e) {
19200                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19201                }
19202
19203                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19204                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19205                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19206                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19207                }
19208            }
19209        }
19210
19211        // Reconcile app data for all started/unlocked users
19212        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19213        final UserManager um = mContext.getSystemService(UserManager.class);
19214        UserManagerInternal umInternal = getUserManagerInternal();
19215        for (UserInfo user : um.getUsers()) {
19216            final int flags;
19217            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19218                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19219            } else if (umInternal.isUserRunning(user.id)) {
19220                flags = StorageManager.FLAG_STORAGE_DE;
19221            } else {
19222                continue;
19223            }
19224
19225            try {
19226                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19227                synchronized (mInstallLock) {
19228                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19229                }
19230            } catch (IllegalStateException e) {
19231                // Device was probably ejected, and we'll process that event momentarily
19232                Slog.w(TAG, "Failed to prepare storage: " + e);
19233            }
19234        }
19235
19236        synchronized (mPackages) {
19237            int updateFlags = UPDATE_PERMISSIONS_ALL;
19238            if (ver.sdkVersion != mSdkVersion) {
19239                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19240                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19241                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19242            }
19243            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19244
19245            // Yay, everything is now upgraded
19246            ver.forceCurrent();
19247
19248            mSettings.writeLPr();
19249        }
19250
19251        for (PackageFreezer freezer : freezers) {
19252            freezer.close();
19253        }
19254
19255        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19256        sendResourcesChangedBroadcast(true, false, loaded, null);
19257    }
19258
19259    private void unloadPrivatePackages(final VolumeInfo vol) {
19260        mHandler.post(new Runnable() {
19261            @Override
19262            public void run() {
19263                unloadPrivatePackagesInner(vol);
19264            }
19265        });
19266    }
19267
19268    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19269        final String volumeUuid = vol.fsUuid;
19270        if (TextUtils.isEmpty(volumeUuid)) {
19271            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19272            return;
19273        }
19274
19275        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19276        synchronized (mInstallLock) {
19277        synchronized (mPackages) {
19278            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19279            for (PackageSetting ps : packages) {
19280                if (ps.pkg == null) continue;
19281
19282                final ApplicationInfo info = ps.pkg.applicationInfo;
19283                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19284                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19285
19286                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19287                        "unloadPrivatePackagesInner")) {
19288                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19289                            false, null)) {
19290                        unloaded.add(info);
19291                    } else {
19292                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19293                    }
19294                }
19295
19296                // Try very hard to release any references to this package
19297                // so we don't risk the system server being killed due to
19298                // open FDs
19299                AttributeCache.instance().removePackage(ps.name);
19300            }
19301
19302            mSettings.writeLPr();
19303        }
19304        }
19305
19306        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19307        sendResourcesChangedBroadcast(false, false, unloaded, null);
19308
19309        // Try very hard to release any references to this path so we don't risk
19310        // the system server being killed due to open FDs
19311        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19312
19313        for (int i = 0; i < 3; i++) {
19314            System.gc();
19315            System.runFinalization();
19316        }
19317    }
19318
19319    /**
19320     * Prepare storage areas for given user on all mounted devices.
19321     */
19322    void prepareUserData(int userId, int userSerial, int flags) {
19323        synchronized (mInstallLock) {
19324            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19325            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19326                final String volumeUuid = vol.getFsUuid();
19327                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19328            }
19329        }
19330    }
19331
19332    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19333            boolean allowRecover) {
19334        // Prepare storage and verify that serial numbers are consistent; if
19335        // there's a mismatch we need to destroy to avoid leaking data
19336        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19337        try {
19338            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19339
19340            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19341                UserManagerService.enforceSerialNumber(
19342                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19343                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19344                    UserManagerService.enforceSerialNumber(
19345                            Environment.getDataSystemDeDirectory(userId), userSerial);
19346                }
19347            }
19348            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19349                UserManagerService.enforceSerialNumber(
19350                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19351                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19352                    UserManagerService.enforceSerialNumber(
19353                            Environment.getDataSystemCeDirectory(userId), userSerial);
19354                }
19355            }
19356
19357            synchronized (mInstallLock) {
19358                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19359            }
19360        } catch (Exception e) {
19361            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19362                    + " because we failed to prepare: " + e);
19363            destroyUserDataLI(volumeUuid, userId,
19364                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19365
19366            if (allowRecover) {
19367                // Try one last time; if we fail again we're really in trouble
19368                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19369            }
19370        }
19371    }
19372
19373    /**
19374     * Destroy storage areas for given user on all mounted devices.
19375     */
19376    void destroyUserData(int userId, int flags) {
19377        synchronized (mInstallLock) {
19378            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19379            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19380                final String volumeUuid = vol.getFsUuid();
19381                destroyUserDataLI(volumeUuid, userId, flags);
19382            }
19383        }
19384    }
19385
19386    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19387        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19388        try {
19389            // Clean up app data, profile data, and media data
19390            mInstaller.destroyUserData(volumeUuid, userId, flags);
19391
19392            // Clean up system data
19393            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19394                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19395                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19396                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19397                }
19398                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19399                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19400                }
19401            }
19402
19403            // Data with special labels is now gone, so finish the job
19404            storage.destroyUserStorage(volumeUuid, userId, flags);
19405
19406        } catch (Exception e) {
19407            logCriticalInfo(Log.WARN,
19408                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19409        }
19410    }
19411
19412    /**
19413     * Examine all users present on given mounted volume, and destroy data
19414     * belonging to users that are no longer valid, or whose user ID has been
19415     * recycled.
19416     */
19417    private void reconcileUsers(String volumeUuid) {
19418        final List<File> files = new ArrayList<>();
19419        Collections.addAll(files, FileUtils
19420                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19421        Collections.addAll(files, FileUtils
19422                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19423        Collections.addAll(files, FileUtils
19424                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19425        Collections.addAll(files, FileUtils
19426                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19427        for (File file : files) {
19428            if (!file.isDirectory()) continue;
19429
19430            final int userId;
19431            final UserInfo info;
19432            try {
19433                userId = Integer.parseInt(file.getName());
19434                info = sUserManager.getUserInfo(userId);
19435            } catch (NumberFormatException e) {
19436                Slog.w(TAG, "Invalid user directory " + file);
19437                continue;
19438            }
19439
19440            boolean destroyUser = false;
19441            if (info == null) {
19442                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19443                        + " because no matching user was found");
19444                destroyUser = true;
19445            } else if (!mOnlyCore) {
19446                try {
19447                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19448                } catch (IOException e) {
19449                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19450                            + " because we failed to enforce serial number: " + e);
19451                    destroyUser = true;
19452                }
19453            }
19454
19455            if (destroyUser) {
19456                synchronized (mInstallLock) {
19457                    destroyUserDataLI(volumeUuid, userId,
19458                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19459                }
19460            }
19461        }
19462    }
19463
19464    private void assertPackageKnown(String volumeUuid, String packageName)
19465            throws PackageManagerException {
19466        synchronized (mPackages) {
19467            final PackageSetting ps = mSettings.mPackages.get(packageName);
19468            if (ps == null) {
19469                throw new PackageManagerException("Package " + packageName + " is unknown");
19470            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19471                throw new PackageManagerException(
19472                        "Package " + packageName + " found on unknown volume " + volumeUuid
19473                                + "; expected volume " + ps.volumeUuid);
19474            }
19475        }
19476    }
19477
19478    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19479            throws PackageManagerException {
19480        synchronized (mPackages) {
19481            final PackageSetting ps = mSettings.mPackages.get(packageName);
19482            if (ps == null) {
19483                throw new PackageManagerException("Package " + packageName + " is unknown");
19484            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19485                throw new PackageManagerException(
19486                        "Package " + packageName + " found on unknown volume " + volumeUuid
19487                                + "; expected volume " + ps.volumeUuid);
19488            } else if (!ps.getInstalled(userId)) {
19489                throw new PackageManagerException(
19490                        "Package " + packageName + " not installed for user " + userId);
19491            }
19492        }
19493    }
19494
19495    /**
19496     * Examine all apps present on given mounted volume, and destroy apps that
19497     * aren't expected, either due to uninstallation or reinstallation on
19498     * another volume.
19499     */
19500    private void reconcileApps(String volumeUuid) {
19501        final File[] files = FileUtils
19502                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19503        for (File file : files) {
19504            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19505                    && !PackageInstallerService.isStageName(file.getName());
19506            if (!isPackage) {
19507                // Ignore entries which are not packages
19508                continue;
19509            }
19510
19511            try {
19512                final PackageLite pkg = PackageParser.parsePackageLite(file,
19513                        PackageParser.PARSE_MUST_BE_APK);
19514                assertPackageKnown(volumeUuid, pkg.packageName);
19515
19516            } catch (PackageParserException | PackageManagerException e) {
19517                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19518                synchronized (mInstallLock) {
19519                    removeCodePathLI(file);
19520                }
19521            }
19522        }
19523    }
19524
19525    /**
19526     * Reconcile all app data for the given user.
19527     * <p>
19528     * Verifies that directories exist and that ownership and labeling is
19529     * correct for all installed apps on all mounted volumes.
19530     */
19531    void reconcileAppsData(int userId, int flags) {
19532        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19533        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19534            final String volumeUuid = vol.getFsUuid();
19535            synchronized (mInstallLock) {
19536                reconcileAppsDataLI(volumeUuid, userId, flags);
19537            }
19538        }
19539    }
19540
19541    /**
19542     * Reconcile all app data on given mounted volume.
19543     * <p>
19544     * Destroys app data that isn't expected, either due to uninstallation or
19545     * reinstallation on another volume.
19546     * <p>
19547     * Verifies that directories exist and that ownership and labeling is
19548     * correct for all installed apps.
19549     */
19550    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19551        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19552                + Integer.toHexString(flags));
19553
19554        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19555        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19556
19557        boolean restoreconNeeded = false;
19558
19559        // First look for stale data that doesn't belong, and check if things
19560        // have changed since we did our last restorecon
19561        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19562            if (StorageManager.isFileEncryptedNativeOrEmulated()
19563                    && !StorageManager.isUserKeyUnlocked(userId)) {
19564                throw new RuntimeException(
19565                        "Yikes, someone asked us to reconcile CE storage while " + userId
19566                                + " was still locked; this would have caused massive data loss!");
19567            }
19568
19569            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19570
19571            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19572            for (File file : files) {
19573                final String packageName = file.getName();
19574                try {
19575                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19576                } catch (PackageManagerException e) {
19577                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19578                    try {
19579                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19580                                StorageManager.FLAG_STORAGE_CE, 0);
19581                    } catch (InstallerException e2) {
19582                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19583                    }
19584                }
19585            }
19586        }
19587        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19588            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19589
19590            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19591            for (File file : files) {
19592                final String packageName = file.getName();
19593                try {
19594                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19595                } catch (PackageManagerException e) {
19596                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19597                    try {
19598                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19599                                StorageManager.FLAG_STORAGE_DE, 0);
19600                    } catch (InstallerException e2) {
19601                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19602                    }
19603                }
19604            }
19605        }
19606
19607        // Ensure that data directories are ready to roll for all packages
19608        // installed for this volume and user
19609        final List<PackageSetting> packages;
19610        synchronized (mPackages) {
19611            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19612        }
19613        int preparedCount = 0;
19614        for (PackageSetting ps : packages) {
19615            final String packageName = ps.name;
19616            if (ps.pkg == null) {
19617                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19618                // TODO: might be due to legacy ASEC apps; we should circle back
19619                // and reconcile again once they're scanned
19620                continue;
19621            }
19622
19623            if (ps.getInstalled(userId)) {
19624                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19625
19626                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19627                    // We may have just shuffled around app data directories, so
19628                    // prepare them one more time
19629                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19630                }
19631
19632                preparedCount++;
19633            }
19634        }
19635
19636        if (restoreconNeeded) {
19637            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19638                SELinuxMMAC.setRestoreconDone(ceDir);
19639            }
19640            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19641                SELinuxMMAC.setRestoreconDone(deDir);
19642            }
19643        }
19644
19645        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19646                + " packages; restoreconNeeded was " + restoreconNeeded);
19647    }
19648
19649    /**
19650     * Prepare app data for the given app just after it was installed or
19651     * upgraded. This method carefully only touches users that it's installed
19652     * for, and it forces a restorecon to handle any seinfo changes.
19653     * <p>
19654     * Verifies that directories exist and that ownership and labeling is
19655     * correct for all installed apps. If there is an ownership mismatch, it
19656     * will try recovering system apps by wiping data; third-party app data is
19657     * left intact.
19658     * <p>
19659     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19660     */
19661    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19662        final PackageSetting ps;
19663        synchronized (mPackages) {
19664            ps = mSettings.mPackages.get(pkg.packageName);
19665            mSettings.writeKernelMappingLPr(ps);
19666        }
19667
19668        final UserManager um = mContext.getSystemService(UserManager.class);
19669        UserManagerInternal umInternal = getUserManagerInternal();
19670        for (UserInfo user : um.getUsers()) {
19671            final int flags;
19672            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19673                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19674            } else if (umInternal.isUserRunning(user.id)) {
19675                flags = StorageManager.FLAG_STORAGE_DE;
19676            } else {
19677                continue;
19678            }
19679
19680            if (ps.getInstalled(user.id)) {
19681                // Whenever an app changes, force a restorecon of its data
19682                // TODO: when user data is locked, mark that we're still dirty
19683                prepareAppDataLIF(pkg, user.id, flags, true);
19684            }
19685        }
19686    }
19687
19688    /**
19689     * Prepare app data for the given app.
19690     * <p>
19691     * Verifies that directories exist and that ownership and labeling is
19692     * correct for all installed apps. If there is an ownership mismatch, this
19693     * will try recovering system apps by wiping data; third-party app data is
19694     * left intact.
19695     */
19696    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19697            boolean restoreconNeeded) {
19698        if (pkg == null) {
19699            Slog.wtf(TAG, "Package was null!", new Throwable());
19700            return;
19701        }
19702        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19703        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19704        for (int i = 0; i < childCount; i++) {
19705            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19706        }
19707    }
19708
19709    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19710            boolean restoreconNeeded) {
19711        if (DEBUG_APP_DATA) {
19712            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19713                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19714        }
19715
19716        final String volumeUuid = pkg.volumeUuid;
19717        final String packageName = pkg.packageName;
19718        final ApplicationInfo app = pkg.applicationInfo;
19719        final int appId = UserHandle.getAppId(app.uid);
19720
19721        Preconditions.checkNotNull(app.seinfo);
19722
19723        try {
19724            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19725                    appId, app.seinfo, app.targetSdkVersion);
19726        } catch (InstallerException e) {
19727            if (app.isSystemApp()) {
19728                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19729                        + ", but trying to recover: " + e);
19730                destroyAppDataLeafLIF(pkg, userId, flags);
19731                try {
19732                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19733                            appId, app.seinfo, app.targetSdkVersion);
19734                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19735                } catch (InstallerException e2) {
19736                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19737                }
19738            } else {
19739                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19740            }
19741        }
19742
19743        if (restoreconNeeded) {
19744            try {
19745                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19746                        app.seinfo);
19747            } catch (InstallerException e) {
19748                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19749            }
19750        }
19751
19752        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19753            try {
19754                // CE storage is unlocked right now, so read out the inode and
19755                // remember for use later when it's locked
19756                // TODO: mark this structure as dirty so we persist it!
19757                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19758                        StorageManager.FLAG_STORAGE_CE);
19759                synchronized (mPackages) {
19760                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19761                    if (ps != null) {
19762                        ps.setCeDataInode(ceDataInode, userId);
19763                    }
19764                }
19765            } catch (InstallerException e) {
19766                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19767            }
19768        }
19769
19770        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19771    }
19772
19773    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19774        if (pkg == null) {
19775            Slog.wtf(TAG, "Package was null!", new Throwable());
19776            return;
19777        }
19778        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19779        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19780        for (int i = 0; i < childCount; i++) {
19781            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19782        }
19783    }
19784
19785    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19786        final String volumeUuid = pkg.volumeUuid;
19787        final String packageName = pkg.packageName;
19788        final ApplicationInfo app = pkg.applicationInfo;
19789
19790        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19791            // Create a native library symlink only if we have native libraries
19792            // and if the native libraries are 32 bit libraries. We do not provide
19793            // this symlink for 64 bit libraries.
19794            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19795                final String nativeLibPath = app.nativeLibraryDir;
19796                try {
19797                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19798                            nativeLibPath, userId);
19799                } catch (InstallerException e) {
19800                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19801                }
19802            }
19803        }
19804    }
19805
19806    /**
19807     * For system apps on non-FBE devices, this method migrates any existing
19808     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19809     * requested by the app.
19810     */
19811    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19812        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19813                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19814            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19815                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19816            try {
19817                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19818                        storageTarget);
19819            } catch (InstallerException e) {
19820                logCriticalInfo(Log.WARN,
19821                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19822            }
19823            return true;
19824        } else {
19825            return false;
19826        }
19827    }
19828
19829    public PackageFreezer freezePackage(String packageName, String killReason) {
19830        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
19831    }
19832
19833    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
19834        return new PackageFreezer(packageName, userId, killReason);
19835    }
19836
19837    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19838            String killReason) {
19839        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
19840    }
19841
19842    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
19843            String killReason) {
19844        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19845            return new PackageFreezer();
19846        } else {
19847            return freezePackage(packageName, userId, killReason);
19848        }
19849    }
19850
19851    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19852            String killReason) {
19853        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
19854    }
19855
19856    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
19857            String killReason) {
19858        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19859            return new PackageFreezer();
19860        } else {
19861            return freezePackage(packageName, userId, killReason);
19862        }
19863    }
19864
19865    /**
19866     * Class that freezes and kills the given package upon creation, and
19867     * unfreezes it upon closing. This is typically used when doing surgery on
19868     * app code/data to prevent the app from running while you're working.
19869     */
19870    private class PackageFreezer implements AutoCloseable {
19871        private final String mPackageName;
19872        private final PackageFreezer[] mChildren;
19873
19874        private final boolean mWeFroze;
19875
19876        private final AtomicBoolean mClosed = new AtomicBoolean();
19877        private final CloseGuard mCloseGuard = CloseGuard.get();
19878
19879        /**
19880         * Create and return a stub freezer that doesn't actually do anything,
19881         * typically used when someone requested
19882         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19883         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19884         */
19885        public PackageFreezer() {
19886            mPackageName = null;
19887            mChildren = null;
19888            mWeFroze = false;
19889            mCloseGuard.open("close");
19890        }
19891
19892        public PackageFreezer(String packageName, int userId, String killReason) {
19893            synchronized (mPackages) {
19894                mPackageName = packageName;
19895                mWeFroze = mFrozenPackages.add(mPackageName);
19896
19897                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19898                if (ps != null) {
19899                    killApplication(ps.name, ps.appId, userId, killReason);
19900                }
19901
19902                final PackageParser.Package p = mPackages.get(packageName);
19903                if (p != null && p.childPackages != null) {
19904                    final int N = p.childPackages.size();
19905                    mChildren = new PackageFreezer[N];
19906                    for (int i = 0; i < N; i++) {
19907                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19908                                userId, killReason);
19909                    }
19910                } else {
19911                    mChildren = null;
19912                }
19913            }
19914            mCloseGuard.open("close");
19915        }
19916
19917        @Override
19918        protected void finalize() throws Throwable {
19919            try {
19920                mCloseGuard.warnIfOpen();
19921                close();
19922            } finally {
19923                super.finalize();
19924            }
19925        }
19926
19927        @Override
19928        public void close() {
19929            mCloseGuard.close();
19930            if (mClosed.compareAndSet(false, true)) {
19931                synchronized (mPackages) {
19932                    if (mWeFroze) {
19933                        mFrozenPackages.remove(mPackageName);
19934                    }
19935
19936                    if (mChildren != null) {
19937                        for (PackageFreezer freezer : mChildren) {
19938                            freezer.close();
19939                        }
19940                    }
19941                }
19942            }
19943        }
19944    }
19945
19946    /**
19947     * Verify that given package is currently frozen.
19948     */
19949    private void checkPackageFrozen(String packageName) {
19950        synchronized (mPackages) {
19951            if (!mFrozenPackages.contains(packageName)) {
19952                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19953            }
19954        }
19955    }
19956
19957    @Override
19958    public int movePackage(final String packageName, final String volumeUuid) {
19959        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19960
19961        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19962        final int moveId = mNextMoveId.getAndIncrement();
19963        mHandler.post(new Runnable() {
19964            @Override
19965            public void run() {
19966                try {
19967                    movePackageInternal(packageName, volumeUuid, moveId, user);
19968                } catch (PackageManagerException e) {
19969                    Slog.w(TAG, "Failed to move " + packageName, e);
19970                    mMoveCallbacks.notifyStatusChanged(moveId,
19971                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19972                }
19973            }
19974        });
19975        return moveId;
19976    }
19977
19978    private void movePackageInternal(final String packageName, final String volumeUuid,
19979            final int moveId, UserHandle user) throws PackageManagerException {
19980        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19981        final PackageManager pm = mContext.getPackageManager();
19982
19983        final boolean currentAsec;
19984        final String currentVolumeUuid;
19985        final File codeFile;
19986        final String installerPackageName;
19987        final String packageAbiOverride;
19988        final int appId;
19989        final String seinfo;
19990        final String label;
19991        final int targetSdkVersion;
19992        final PackageFreezer freezer;
19993        final int[] installedUserIds;
19994
19995        // reader
19996        synchronized (mPackages) {
19997            final PackageParser.Package pkg = mPackages.get(packageName);
19998            final PackageSetting ps = mSettings.mPackages.get(packageName);
19999            if (pkg == null || ps == null) {
20000                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20001            }
20002
20003            if (pkg.applicationInfo.isSystemApp()) {
20004                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20005                        "Cannot move system application");
20006            }
20007
20008            if (pkg.applicationInfo.isExternalAsec()) {
20009                currentAsec = true;
20010                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20011            } else if (pkg.applicationInfo.isForwardLocked()) {
20012                currentAsec = true;
20013                currentVolumeUuid = "forward_locked";
20014            } else {
20015                currentAsec = false;
20016                currentVolumeUuid = ps.volumeUuid;
20017
20018                final File probe = new File(pkg.codePath);
20019                final File probeOat = new File(probe, "oat");
20020                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20021                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20022                            "Move only supported for modern cluster style installs");
20023                }
20024            }
20025
20026            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20027                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20028                        "Package already moved to " + volumeUuid);
20029            }
20030            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20031                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20032                        "Device admin cannot be moved");
20033            }
20034
20035            if (mFrozenPackages.contains(packageName)) {
20036                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20037                        "Failed to move already frozen package");
20038            }
20039
20040            codeFile = new File(pkg.codePath);
20041            installerPackageName = ps.installerPackageName;
20042            packageAbiOverride = ps.cpuAbiOverrideString;
20043            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20044            seinfo = pkg.applicationInfo.seinfo;
20045            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20046            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20047            freezer = freezePackage(packageName, "movePackageInternal");
20048            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20049        }
20050
20051        final Bundle extras = new Bundle();
20052        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20053        extras.putString(Intent.EXTRA_TITLE, label);
20054        mMoveCallbacks.notifyCreated(moveId, extras);
20055
20056        int installFlags;
20057        final boolean moveCompleteApp;
20058        final File measurePath;
20059
20060        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20061            installFlags = INSTALL_INTERNAL;
20062            moveCompleteApp = !currentAsec;
20063            measurePath = Environment.getDataAppDirectory(volumeUuid);
20064        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20065            installFlags = INSTALL_EXTERNAL;
20066            moveCompleteApp = false;
20067            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20068        } else {
20069            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20070            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20071                    || !volume.isMountedWritable()) {
20072                freezer.close();
20073                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20074                        "Move location not mounted private volume");
20075            }
20076
20077            Preconditions.checkState(!currentAsec);
20078
20079            installFlags = INSTALL_INTERNAL;
20080            moveCompleteApp = true;
20081            measurePath = Environment.getDataAppDirectory(volumeUuid);
20082        }
20083
20084        final PackageStats stats = new PackageStats(null, -1);
20085        synchronized (mInstaller) {
20086            for (int userId : installedUserIds) {
20087                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20088                    freezer.close();
20089                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20090                            "Failed to measure package size");
20091                }
20092            }
20093        }
20094
20095        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20096                + stats.dataSize);
20097
20098        final long startFreeBytes = measurePath.getFreeSpace();
20099        final long sizeBytes;
20100        if (moveCompleteApp) {
20101            sizeBytes = stats.codeSize + stats.dataSize;
20102        } else {
20103            sizeBytes = stats.codeSize;
20104        }
20105
20106        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20107            freezer.close();
20108            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20109                    "Not enough free space to move");
20110        }
20111
20112        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20113
20114        final CountDownLatch installedLatch = new CountDownLatch(1);
20115        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20116            @Override
20117            public void onUserActionRequired(Intent intent) throws RemoteException {
20118                throw new IllegalStateException();
20119            }
20120
20121            @Override
20122            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20123                    Bundle extras) throws RemoteException {
20124                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20125                        + PackageManager.installStatusToString(returnCode, msg));
20126
20127                installedLatch.countDown();
20128                freezer.close();
20129
20130                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20131                switch (status) {
20132                    case PackageInstaller.STATUS_SUCCESS:
20133                        mMoveCallbacks.notifyStatusChanged(moveId,
20134                                PackageManager.MOVE_SUCCEEDED);
20135                        break;
20136                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20137                        mMoveCallbacks.notifyStatusChanged(moveId,
20138                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20139                        break;
20140                    default:
20141                        mMoveCallbacks.notifyStatusChanged(moveId,
20142                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20143                        break;
20144                }
20145            }
20146        };
20147
20148        final MoveInfo move;
20149        if (moveCompleteApp) {
20150            // Kick off a thread to report progress estimates
20151            new Thread() {
20152                @Override
20153                public void run() {
20154                    while (true) {
20155                        try {
20156                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20157                                break;
20158                            }
20159                        } catch (InterruptedException ignored) {
20160                        }
20161
20162                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20163                        final int progress = 10 + (int) MathUtils.constrain(
20164                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20165                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20166                    }
20167                }
20168            }.start();
20169
20170            final String dataAppName = codeFile.getName();
20171            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20172                    dataAppName, appId, seinfo, targetSdkVersion);
20173        } else {
20174            move = null;
20175        }
20176
20177        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20178
20179        final Message msg = mHandler.obtainMessage(INIT_COPY);
20180        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20181        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20182                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20183                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20184        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20185        msg.obj = params;
20186
20187        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20188                System.identityHashCode(msg.obj));
20189        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20190                System.identityHashCode(msg.obj));
20191
20192        mHandler.sendMessage(msg);
20193    }
20194
20195    @Override
20196    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20197        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20198
20199        final int realMoveId = mNextMoveId.getAndIncrement();
20200        final Bundle extras = new Bundle();
20201        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20202        mMoveCallbacks.notifyCreated(realMoveId, extras);
20203
20204        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20205            @Override
20206            public void onCreated(int moveId, Bundle extras) {
20207                // Ignored
20208            }
20209
20210            @Override
20211            public void onStatusChanged(int moveId, int status, long estMillis) {
20212                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20213            }
20214        };
20215
20216        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20217        storage.setPrimaryStorageUuid(volumeUuid, callback);
20218        return realMoveId;
20219    }
20220
20221    @Override
20222    public int getMoveStatus(int moveId) {
20223        mContext.enforceCallingOrSelfPermission(
20224                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20225        return mMoveCallbacks.mLastStatus.get(moveId);
20226    }
20227
20228    @Override
20229    public void registerMoveCallback(IPackageMoveObserver callback) {
20230        mContext.enforceCallingOrSelfPermission(
20231                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20232        mMoveCallbacks.register(callback);
20233    }
20234
20235    @Override
20236    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20237        mContext.enforceCallingOrSelfPermission(
20238                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20239        mMoveCallbacks.unregister(callback);
20240    }
20241
20242    @Override
20243    public boolean setInstallLocation(int loc) {
20244        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20245                null);
20246        if (getInstallLocation() == loc) {
20247            return true;
20248        }
20249        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20250                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20251            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20252                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20253            return true;
20254        }
20255        return false;
20256   }
20257
20258    @Override
20259    public int getInstallLocation() {
20260        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20261                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20262                PackageHelper.APP_INSTALL_AUTO);
20263    }
20264
20265    /** Called by UserManagerService */
20266    void cleanUpUser(UserManagerService userManager, int userHandle) {
20267        synchronized (mPackages) {
20268            mDirtyUsers.remove(userHandle);
20269            mUserNeedsBadging.delete(userHandle);
20270            mSettings.removeUserLPw(userHandle);
20271            mPendingBroadcasts.remove(userHandle);
20272            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20273            removeUnusedPackagesLPw(userManager, userHandle);
20274        }
20275    }
20276
20277    /**
20278     * We're removing userHandle and would like to remove any downloaded packages
20279     * that are no longer in use by any other user.
20280     * @param userHandle the user being removed
20281     */
20282    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20283        final boolean DEBUG_CLEAN_APKS = false;
20284        int [] users = userManager.getUserIds();
20285        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20286        while (psit.hasNext()) {
20287            PackageSetting ps = psit.next();
20288            if (ps.pkg == null) {
20289                continue;
20290            }
20291            final String packageName = ps.pkg.packageName;
20292            // Skip over if system app
20293            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20294                continue;
20295            }
20296            if (DEBUG_CLEAN_APKS) {
20297                Slog.i(TAG, "Checking package " + packageName);
20298            }
20299            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20300            if (keep) {
20301                if (DEBUG_CLEAN_APKS) {
20302                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20303                }
20304            } else {
20305                for (int i = 0; i < users.length; i++) {
20306                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20307                        keep = true;
20308                        if (DEBUG_CLEAN_APKS) {
20309                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20310                                    + users[i]);
20311                        }
20312                        break;
20313                    }
20314                }
20315            }
20316            if (!keep) {
20317                if (DEBUG_CLEAN_APKS) {
20318                    Slog.i(TAG, "  Removing package " + packageName);
20319                }
20320                mHandler.post(new Runnable() {
20321                    public void run() {
20322                        deletePackageX(packageName, userHandle, 0);
20323                    } //end run
20324                });
20325            }
20326        }
20327    }
20328
20329    /** Called by UserManagerService */
20330    void createNewUser(int userId) {
20331        synchronized (mInstallLock) {
20332            mSettings.createNewUserLI(this, mInstaller, userId);
20333        }
20334        synchronized (mPackages) {
20335            scheduleWritePackageRestrictionsLocked(userId);
20336            scheduleWritePackageListLocked(userId);
20337            applyFactoryDefaultBrowserLPw(userId);
20338            primeDomainVerificationsLPw(userId);
20339        }
20340    }
20341
20342    void onNewUserCreated(final int userId) {
20343        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20344        // If permission review for legacy apps is required, we represent
20345        // dagerous permissions for such apps as always granted runtime
20346        // permissions to keep per user flag state whether review is needed.
20347        // Hence, if a new user is added we have to propagate dangerous
20348        // permission grants for these legacy apps.
20349        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20350            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20351                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20352        }
20353    }
20354
20355    @Override
20356    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20357        mContext.enforceCallingOrSelfPermission(
20358                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20359                "Only package verification agents can read the verifier device identity");
20360
20361        synchronized (mPackages) {
20362            return mSettings.getVerifierDeviceIdentityLPw();
20363        }
20364    }
20365
20366    @Override
20367    public void setPermissionEnforced(String permission, boolean enforced) {
20368        // TODO: Now that we no longer change GID for storage, this should to away.
20369        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20370                "setPermissionEnforced");
20371        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20372            synchronized (mPackages) {
20373                if (mSettings.mReadExternalStorageEnforced == null
20374                        || mSettings.mReadExternalStorageEnforced != enforced) {
20375                    mSettings.mReadExternalStorageEnforced = enforced;
20376                    mSettings.writeLPr();
20377                }
20378            }
20379            // kill any non-foreground processes so we restart them and
20380            // grant/revoke the GID.
20381            final IActivityManager am = ActivityManagerNative.getDefault();
20382            if (am != null) {
20383                final long token = Binder.clearCallingIdentity();
20384                try {
20385                    am.killProcessesBelowForeground("setPermissionEnforcement");
20386                } catch (RemoteException e) {
20387                } finally {
20388                    Binder.restoreCallingIdentity(token);
20389                }
20390            }
20391        } else {
20392            throw new IllegalArgumentException("No selective enforcement for " + permission);
20393        }
20394    }
20395
20396    @Override
20397    @Deprecated
20398    public boolean isPermissionEnforced(String permission) {
20399        return true;
20400    }
20401
20402    @Override
20403    public boolean isStorageLow() {
20404        final long token = Binder.clearCallingIdentity();
20405        try {
20406            final DeviceStorageMonitorInternal
20407                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20408            if (dsm != null) {
20409                return dsm.isMemoryLow();
20410            } else {
20411                return false;
20412            }
20413        } finally {
20414            Binder.restoreCallingIdentity(token);
20415        }
20416    }
20417
20418    @Override
20419    public IPackageInstaller getPackageInstaller() {
20420        return mInstallerService;
20421    }
20422
20423    private boolean userNeedsBadging(int userId) {
20424        int index = mUserNeedsBadging.indexOfKey(userId);
20425        if (index < 0) {
20426            final UserInfo userInfo;
20427            final long token = Binder.clearCallingIdentity();
20428            try {
20429                userInfo = sUserManager.getUserInfo(userId);
20430            } finally {
20431                Binder.restoreCallingIdentity(token);
20432            }
20433            final boolean b;
20434            if (userInfo != null && userInfo.isManagedProfile()) {
20435                b = true;
20436            } else {
20437                b = false;
20438            }
20439            mUserNeedsBadging.put(userId, b);
20440            return b;
20441        }
20442        return mUserNeedsBadging.valueAt(index);
20443    }
20444
20445    @Override
20446    public KeySet getKeySetByAlias(String packageName, String alias) {
20447        if (packageName == null || alias == null) {
20448            return null;
20449        }
20450        synchronized(mPackages) {
20451            final PackageParser.Package pkg = mPackages.get(packageName);
20452            if (pkg == null) {
20453                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20454                throw new IllegalArgumentException("Unknown package: " + packageName);
20455            }
20456            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20457            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20458        }
20459    }
20460
20461    @Override
20462    public KeySet getSigningKeySet(String packageName) {
20463        if (packageName == null) {
20464            return null;
20465        }
20466        synchronized(mPackages) {
20467            final PackageParser.Package pkg = mPackages.get(packageName);
20468            if (pkg == null) {
20469                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20470                throw new IllegalArgumentException("Unknown package: " + packageName);
20471            }
20472            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20473                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20474                throw new SecurityException("May not access signing KeySet of other apps.");
20475            }
20476            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20477            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20478        }
20479    }
20480
20481    @Override
20482    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20483        if (packageName == null || ks == null) {
20484            return false;
20485        }
20486        synchronized(mPackages) {
20487            final PackageParser.Package pkg = mPackages.get(packageName);
20488            if (pkg == null) {
20489                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20490                throw new IllegalArgumentException("Unknown package: " + packageName);
20491            }
20492            IBinder ksh = ks.getToken();
20493            if (ksh instanceof KeySetHandle) {
20494                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20495                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20496            }
20497            return false;
20498        }
20499    }
20500
20501    @Override
20502    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20503        if (packageName == null || ks == null) {
20504            return false;
20505        }
20506        synchronized(mPackages) {
20507            final PackageParser.Package pkg = mPackages.get(packageName);
20508            if (pkg == null) {
20509                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20510                throw new IllegalArgumentException("Unknown package: " + packageName);
20511            }
20512            IBinder ksh = ks.getToken();
20513            if (ksh instanceof KeySetHandle) {
20514                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20515                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20516            }
20517            return false;
20518        }
20519    }
20520
20521    private void deletePackageIfUnusedLPr(final String packageName) {
20522        PackageSetting ps = mSettings.mPackages.get(packageName);
20523        if (ps == null) {
20524            return;
20525        }
20526        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20527            // TODO Implement atomic delete if package is unused
20528            // It is currently possible that the package will be deleted even if it is installed
20529            // after this method returns.
20530            mHandler.post(new Runnable() {
20531                public void run() {
20532                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20533                }
20534            });
20535        }
20536    }
20537
20538    /**
20539     * Check and throw if the given before/after packages would be considered a
20540     * downgrade.
20541     */
20542    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20543            throws PackageManagerException {
20544        if (after.versionCode < before.mVersionCode) {
20545            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20546                    "Update version code " + after.versionCode + " is older than current "
20547                    + before.mVersionCode);
20548        } else if (after.versionCode == before.mVersionCode) {
20549            if (after.baseRevisionCode < before.baseRevisionCode) {
20550                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20551                        "Update base revision code " + after.baseRevisionCode
20552                        + " is older than current " + before.baseRevisionCode);
20553            }
20554
20555            if (!ArrayUtils.isEmpty(after.splitNames)) {
20556                for (int i = 0; i < after.splitNames.length; i++) {
20557                    final String splitName = after.splitNames[i];
20558                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20559                    if (j != -1) {
20560                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20561                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20562                                    "Update split " + splitName + " revision code "
20563                                    + after.splitRevisionCodes[i] + " is older than current "
20564                                    + before.splitRevisionCodes[j]);
20565                        }
20566                    }
20567                }
20568            }
20569        }
20570    }
20571
20572    private static class MoveCallbacks extends Handler {
20573        private static final int MSG_CREATED = 1;
20574        private static final int MSG_STATUS_CHANGED = 2;
20575
20576        private final RemoteCallbackList<IPackageMoveObserver>
20577                mCallbacks = new RemoteCallbackList<>();
20578
20579        private final SparseIntArray mLastStatus = new SparseIntArray();
20580
20581        public MoveCallbacks(Looper looper) {
20582            super(looper);
20583        }
20584
20585        public void register(IPackageMoveObserver callback) {
20586            mCallbacks.register(callback);
20587        }
20588
20589        public void unregister(IPackageMoveObserver callback) {
20590            mCallbacks.unregister(callback);
20591        }
20592
20593        @Override
20594        public void handleMessage(Message msg) {
20595            final SomeArgs args = (SomeArgs) msg.obj;
20596            final int n = mCallbacks.beginBroadcast();
20597            for (int i = 0; i < n; i++) {
20598                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20599                try {
20600                    invokeCallback(callback, msg.what, args);
20601                } catch (RemoteException ignored) {
20602                }
20603            }
20604            mCallbacks.finishBroadcast();
20605            args.recycle();
20606        }
20607
20608        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20609                throws RemoteException {
20610            switch (what) {
20611                case MSG_CREATED: {
20612                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20613                    break;
20614                }
20615                case MSG_STATUS_CHANGED: {
20616                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20617                    break;
20618                }
20619            }
20620        }
20621
20622        private void notifyCreated(int moveId, Bundle extras) {
20623            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20624
20625            final SomeArgs args = SomeArgs.obtain();
20626            args.argi1 = moveId;
20627            args.arg2 = extras;
20628            obtainMessage(MSG_CREATED, args).sendToTarget();
20629        }
20630
20631        private void notifyStatusChanged(int moveId, int status) {
20632            notifyStatusChanged(moveId, status, -1);
20633        }
20634
20635        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20636            Slog.v(TAG, "Move " + moveId + " status " + status);
20637
20638            final SomeArgs args = SomeArgs.obtain();
20639            args.argi1 = moveId;
20640            args.argi2 = status;
20641            args.arg3 = estMillis;
20642            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20643
20644            synchronized (mLastStatus) {
20645                mLastStatus.put(moveId, status);
20646            }
20647        }
20648    }
20649
20650    private final static class OnPermissionChangeListeners extends Handler {
20651        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20652
20653        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20654                new RemoteCallbackList<>();
20655
20656        public OnPermissionChangeListeners(Looper looper) {
20657            super(looper);
20658        }
20659
20660        @Override
20661        public void handleMessage(Message msg) {
20662            switch (msg.what) {
20663                case MSG_ON_PERMISSIONS_CHANGED: {
20664                    final int uid = msg.arg1;
20665                    handleOnPermissionsChanged(uid);
20666                } break;
20667            }
20668        }
20669
20670        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20671            mPermissionListeners.register(listener);
20672
20673        }
20674
20675        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20676            mPermissionListeners.unregister(listener);
20677        }
20678
20679        public void onPermissionsChanged(int uid) {
20680            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20681                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20682            }
20683        }
20684
20685        private void handleOnPermissionsChanged(int uid) {
20686            final int count = mPermissionListeners.beginBroadcast();
20687            try {
20688                for (int i = 0; i < count; i++) {
20689                    IOnPermissionsChangeListener callback = mPermissionListeners
20690                            .getBroadcastItem(i);
20691                    try {
20692                        callback.onPermissionsChanged(uid);
20693                    } catch (RemoteException e) {
20694                        Log.e(TAG, "Permission listener is dead", e);
20695                    }
20696                }
20697            } finally {
20698                mPermissionListeners.finishBroadcast();
20699            }
20700        }
20701    }
20702
20703    private class PackageManagerInternalImpl extends PackageManagerInternal {
20704        @Override
20705        public void setLocationPackagesProvider(PackagesProvider provider) {
20706            synchronized (mPackages) {
20707                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20708            }
20709        }
20710
20711        @Override
20712        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20713            synchronized (mPackages) {
20714                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20715            }
20716        }
20717
20718        @Override
20719        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20720            synchronized (mPackages) {
20721                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20722            }
20723        }
20724
20725        @Override
20726        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20727            synchronized (mPackages) {
20728                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20729            }
20730        }
20731
20732        @Override
20733        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20734            synchronized (mPackages) {
20735                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20736            }
20737        }
20738
20739        @Override
20740        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20741            synchronized (mPackages) {
20742                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20743            }
20744        }
20745
20746        @Override
20747        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20748            synchronized (mPackages) {
20749                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20750                        packageName, userId);
20751            }
20752        }
20753
20754        @Override
20755        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20756            synchronized (mPackages) {
20757                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20758                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20759                        packageName, userId);
20760            }
20761        }
20762
20763        @Override
20764        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20765            synchronized (mPackages) {
20766                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20767                        packageName, userId);
20768            }
20769        }
20770
20771        @Override
20772        public void setKeepUninstalledPackages(final List<String> packageList) {
20773            Preconditions.checkNotNull(packageList);
20774            List<String> removedFromList = null;
20775            synchronized (mPackages) {
20776                if (mKeepUninstalledPackages != null) {
20777                    final int packagesCount = mKeepUninstalledPackages.size();
20778                    for (int i = 0; i < packagesCount; i++) {
20779                        String oldPackage = mKeepUninstalledPackages.get(i);
20780                        if (packageList != null && packageList.contains(oldPackage)) {
20781                            continue;
20782                        }
20783                        if (removedFromList == null) {
20784                            removedFromList = new ArrayList<>();
20785                        }
20786                        removedFromList.add(oldPackage);
20787                    }
20788                }
20789                mKeepUninstalledPackages = new ArrayList<>(packageList);
20790                if (removedFromList != null) {
20791                    final int removedCount = removedFromList.size();
20792                    for (int i = 0; i < removedCount; i++) {
20793                        deletePackageIfUnusedLPr(removedFromList.get(i));
20794                    }
20795                }
20796            }
20797        }
20798
20799        @Override
20800        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20801            synchronized (mPackages) {
20802                // If we do not support permission review, done.
20803                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20804                    return false;
20805                }
20806
20807                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20808                if (packageSetting == null) {
20809                    return false;
20810                }
20811
20812                // Permission review applies only to apps not supporting the new permission model.
20813                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20814                    return false;
20815                }
20816
20817                // Legacy apps have the permission and get user consent on launch.
20818                PermissionsState permissionsState = packageSetting.getPermissionsState();
20819                return permissionsState.isPermissionReviewRequired(userId);
20820            }
20821        }
20822
20823        @Override
20824        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20825            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20826        }
20827
20828        @Override
20829        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20830                int userId) {
20831            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20832        }
20833
20834        @Override
20835        public void setDeviceAndProfileOwnerPackages(
20836                int deviceOwnerUserId, String deviceOwnerPackage,
20837                SparseArray<String> profileOwnerPackages) {
20838            mProtectedPackages.setDeviceAndProfileOwnerPackages(
20839                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
20840        }
20841
20842        @Override
20843        public boolean isPackageDataProtected(int userId, String packageName) {
20844            return mProtectedPackages.isPackageDataProtected(userId, packageName);
20845        }
20846    }
20847
20848    @Override
20849    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20850        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20851        synchronized (mPackages) {
20852            final long identity = Binder.clearCallingIdentity();
20853            try {
20854                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20855                        packageNames, userId);
20856            } finally {
20857                Binder.restoreCallingIdentity(identity);
20858            }
20859        }
20860    }
20861
20862    private static void enforceSystemOrPhoneCaller(String tag) {
20863        int callingUid = Binder.getCallingUid();
20864        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20865            throw new SecurityException(
20866                    "Cannot call " + tag + " from UID " + callingUid);
20867        }
20868    }
20869
20870    boolean isHistoricalPackageUsageAvailable() {
20871        return mPackageUsage.isHistoricalPackageUsageAvailable();
20872    }
20873
20874    /**
20875     * Return a <b>copy</b> of the collection of packages known to the package manager.
20876     * @return A copy of the values of mPackages.
20877     */
20878    Collection<PackageParser.Package> getPackages() {
20879        synchronized (mPackages) {
20880            return new ArrayList<>(mPackages.values());
20881        }
20882    }
20883
20884    /**
20885     * Logs process start information (including base APK hash) to the security log.
20886     * @hide
20887     */
20888    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20889            String apkFile, int pid) {
20890        if (!SecurityLog.isLoggingEnabled()) {
20891            return;
20892        }
20893        Bundle data = new Bundle();
20894        data.putLong("startTimestamp", System.currentTimeMillis());
20895        data.putString("processName", processName);
20896        data.putInt("uid", uid);
20897        data.putString("seinfo", seinfo);
20898        data.putString("apkFile", apkFile);
20899        data.putInt("pid", pid);
20900        Message msg = mProcessLoggingHandler.obtainMessage(
20901                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20902        msg.setData(data);
20903        mProcessLoggingHandler.sendMessage(msg);
20904    }
20905
20906    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
20907        return mCompilerStats.getPackageStats(pkgName);
20908    }
20909
20910    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
20911        return getOrCreateCompilerPackageStats(pkg.packageName);
20912    }
20913
20914    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
20915        return mCompilerStats.getOrCreatePackageStats(pkgName);
20916    }
20917
20918    public void deleteCompilerPackageStats(String pkgName) {
20919        mCompilerStats.deletePackageStats(pkgName);
20920    }
20921}
20922