PackageManagerService.java revision 21bd9b824f1bed7ccb412f1cd27e3f3a159ffe19
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55import static android.content.pm.PackageManager.INSTALL_INTERNAL;
56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
62import static android.content.pm.PackageManager.MATCH_ALL;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
75import static android.content.pm.PackageManager.PERMISSION_DENIED;
76import static android.content.pm.PackageManager.PERMISSION_GRANTED;
77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
78import static android.content.pm.PackageParser.isApkFile;
79import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
80import static android.system.OsConstants.O_CREAT;
81import static android.system.OsConstants.O_RDWR;
82
83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
85import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
86import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
87import static com.android.internal.util.ArrayUtils.appendInt;
88import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
89import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
92import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
93import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
100
101import android.Manifest;
102import android.annotation.NonNull;
103import android.annotation.Nullable;
104import android.annotation.UserIdInt;
105import android.app.ActivityManager;
106import android.app.ActivityManagerNative;
107import android.app.IActivityManager;
108import android.app.ResourcesManager;
109import android.app.admin.IDevicePolicyManager;
110import android.app.admin.SecurityLog;
111import android.app.backup.IBackupManager;
112import android.content.BroadcastReceiver;
113import android.content.ComponentName;
114import android.content.Context;
115import android.content.IIntentReceiver;
116import android.content.Intent;
117import android.content.IntentFilter;
118import android.content.IntentSender;
119import android.content.IntentSender.SendIntentException;
120import android.content.ServiceConnection;
121import android.content.pm.ActivityInfo;
122import android.content.pm.ApplicationInfo;
123import android.content.pm.AppsQueryHelper;
124import android.content.pm.ComponentInfo;
125import android.content.pm.EphemeralApplicationInfo;
126import android.content.pm.EphemeralResolveInfo;
127import android.content.pm.EphemeralResolveInfo.EphemeralDigest;
128import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
129import android.content.pm.FeatureInfo;
130import android.content.pm.IOnPermissionsChangeListener;
131import android.content.pm.IPackageDataObserver;
132import android.content.pm.IPackageDeleteObserver;
133import android.content.pm.IPackageDeleteObserver2;
134import android.content.pm.IPackageInstallObserver2;
135import android.content.pm.IPackageInstaller;
136import android.content.pm.IPackageManager;
137import android.content.pm.IPackageMoveObserver;
138import android.content.pm.IPackageStatsObserver;
139import android.content.pm.InstrumentationInfo;
140import android.content.pm.IntentFilterVerificationInfo;
141import android.content.pm.KeySet;
142import android.content.pm.PackageCleanItem;
143import android.content.pm.PackageInfo;
144import android.content.pm.PackageInfoLite;
145import android.content.pm.PackageInstaller;
146import android.content.pm.PackageManager;
147import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
148import android.content.pm.PackageManagerInternal;
149import android.content.pm.PackageParser;
150import android.content.pm.PackageParser.ActivityIntentInfo;
151import android.content.pm.PackageParser.PackageLite;
152import android.content.pm.PackageParser.PackageParserException;
153import android.content.pm.PackageStats;
154import android.content.pm.PackageUserState;
155import android.content.pm.ParceledListSlice;
156import android.content.pm.PermissionGroupInfo;
157import android.content.pm.PermissionInfo;
158import android.content.pm.ProviderInfo;
159import android.content.pm.ResolveInfo;
160import android.content.pm.ServiceInfo;
161import android.content.pm.Signature;
162import android.content.pm.UserInfo;
163import android.content.pm.VerifierDeviceIdentity;
164import android.content.pm.VerifierInfo;
165import android.content.res.Resources;
166import android.graphics.Bitmap;
167import android.hardware.display.DisplayManager;
168import android.net.Uri;
169import android.os.Binder;
170import android.os.Build;
171import android.os.Bundle;
172import android.os.Debug;
173import android.os.Environment;
174import android.os.Environment.UserEnvironment;
175import android.os.FileUtils;
176import android.os.Handler;
177import android.os.IBinder;
178import android.os.Looper;
179import android.os.Message;
180import android.os.Parcel;
181import android.os.ParcelFileDescriptor;
182import android.os.Process;
183import android.os.RemoteCallbackList;
184import android.os.RemoteException;
185import android.os.ResultReceiver;
186import android.os.SELinux;
187import android.os.ServiceManager;
188import android.os.SystemClock;
189import android.os.SystemProperties;
190import android.os.Trace;
191import android.os.UserHandle;
192import android.os.UserManager;
193import android.os.UserManagerInternal;
194import android.os.storage.IMountService;
195import android.os.storage.MountServiceInternal;
196import android.os.storage.StorageEventListener;
197import android.os.storage.StorageManager;
198import android.os.storage.VolumeInfo;
199import android.os.storage.VolumeRecord;
200import android.provider.Settings.Global;
201import android.security.KeyStore;
202import android.security.SystemKeyStore;
203import android.system.ErrnoException;
204import android.system.Os;
205import android.text.TextUtils;
206import android.text.format.DateUtils;
207import android.util.ArrayMap;
208import android.util.ArraySet;
209import android.util.DisplayMetrics;
210import android.util.EventLog;
211import android.util.ExceptionUtils;
212import android.util.Log;
213import android.util.LogPrinter;
214import android.util.MathUtils;
215import android.util.PrintStreamPrinter;
216import android.util.Slog;
217import android.util.SparseArray;
218import android.util.SparseBooleanArray;
219import android.util.SparseIntArray;
220import android.util.Xml;
221import android.util.jar.StrictJarFile;
222import android.view.Display;
223
224import com.android.internal.R;
225import com.android.internal.annotations.GuardedBy;
226import com.android.internal.app.IMediaContainerService;
227import com.android.internal.app.ResolverActivity;
228import com.android.internal.content.NativeLibraryHelper;
229import com.android.internal.content.PackageHelper;
230import com.android.internal.logging.MetricsLogger;
231import com.android.internal.os.IParcelFileDescriptorFactory;
232import com.android.internal.os.InstallerConnection.InstallerException;
233import com.android.internal.os.SomeArgs;
234import com.android.internal.os.Zygote;
235import com.android.internal.telephony.CarrierAppUtils;
236import com.android.internal.util.ArrayUtils;
237import com.android.internal.util.FastPrintWriter;
238import com.android.internal.util.FastXmlSerializer;
239import com.android.internal.util.IndentingPrintWriter;
240import com.android.internal.util.Preconditions;
241import com.android.internal.util.XmlUtils;
242import com.android.server.AttributeCache;
243import com.android.server.EventLogTags;
244import com.android.server.FgThread;
245import com.android.server.IntentResolver;
246import com.android.server.LocalServices;
247import com.android.server.ServiceThread;
248import com.android.server.SystemConfig;
249import com.android.server.Watchdog;
250import com.android.server.net.NetworkPolicyManagerInternal;
251import com.android.server.pm.PermissionsState.PermissionState;
252import com.android.server.pm.Settings.DatabaseVersion;
253import com.android.server.pm.Settings.VersionInfo;
254import com.android.server.storage.DeviceStorageMonitorInternal;
255
256import dalvik.system.CloseGuard;
257import dalvik.system.DexFile;
258import dalvik.system.VMRuntime;
259
260import libcore.io.IoUtils;
261import libcore.util.EmptyArray;
262
263import org.xmlpull.v1.XmlPullParser;
264import org.xmlpull.v1.XmlPullParserException;
265import org.xmlpull.v1.XmlSerializer;
266
267import java.io.BufferedOutputStream;
268import java.io.BufferedReader;
269import java.io.ByteArrayInputStream;
270import java.io.ByteArrayOutputStream;
271import java.io.File;
272import java.io.FileDescriptor;
273import java.io.FileInputStream;
274import java.io.FileNotFoundException;
275import java.io.FileOutputStream;
276import java.io.FileReader;
277import java.io.FilenameFilter;
278import java.io.IOException;
279import java.io.PrintWriter;
280import java.nio.charset.StandardCharsets;
281import java.security.DigestInputStream;
282import java.security.MessageDigest;
283import java.security.NoSuchAlgorithmException;
284import java.security.PublicKey;
285import java.security.cert.Certificate;
286import java.security.cert.CertificateEncodingException;
287import java.security.cert.CertificateException;
288import java.text.SimpleDateFormat;
289import java.util.ArrayList;
290import java.util.Arrays;
291import java.util.Collection;
292import java.util.Collections;
293import java.util.Comparator;
294import java.util.Date;
295import java.util.HashSet;
296import java.util.Iterator;
297import java.util.List;
298import java.util.Map;
299import java.util.Objects;
300import java.util.Set;
301import java.util.concurrent.CountDownLatch;
302import java.util.concurrent.TimeUnit;
303import java.util.concurrent.atomic.AtomicBoolean;
304import java.util.concurrent.atomic.AtomicInteger;
305
306/**
307 * Keep track of all those APKs everywhere.
308 * <p>
309 * Internally there are two important locks:
310 * <ul>
311 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
312 * and other related state. It is a fine-grained lock that should only be held
313 * momentarily, as it's one of the most contended locks in the system.
314 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
315 * operations typically involve heavy lifting of application data on disk. Since
316 * {@code installd} is single-threaded, and it's operations can often be slow,
317 * this lock should never be acquired while already holding {@link #mPackages}.
318 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
319 * holding {@link #mInstallLock}.
320 * </ul>
321 * Many internal methods rely on the caller to hold the appropriate locks, and
322 * this contract is expressed through method name suffixes:
323 * <ul>
324 * <li>fooLI(): the caller must hold {@link #mInstallLock}
325 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
326 * being modified must be frozen
327 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
328 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
329 * </ul>
330 * <p>
331 * Because this class is very central to the platform's security; please run all
332 * CTS and unit tests whenever making modifications:
333 *
334 * <pre>
335 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
336 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
337 * </pre>
338 */
339public class PackageManagerService extends IPackageManager.Stub {
340    static final String TAG = "PackageManager";
341    static final boolean DEBUG_SETTINGS = false;
342    static final boolean DEBUG_PREFERRED = false;
343    static final boolean DEBUG_UPGRADE = false;
344    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
345    private static final boolean DEBUG_BACKUP = false;
346    private static final boolean DEBUG_INSTALL = false;
347    private static final boolean DEBUG_REMOVE = false;
348    private static final boolean DEBUG_BROADCASTS = false;
349    private static final boolean DEBUG_SHOW_INFO = false;
350    private static final boolean DEBUG_PACKAGE_INFO = false;
351    private static final boolean DEBUG_INTENT_MATCHING = false;
352    private static final boolean DEBUG_PACKAGE_SCANNING = false;
353    private static final boolean DEBUG_VERIFY = false;
354    private static final boolean DEBUG_FILTERS = false;
355
356    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
357    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
358    // user, but by default initialize to this.
359    static final boolean DEBUG_DEXOPT = false;
360
361    private static final boolean DEBUG_ABI_SELECTION = false;
362    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
363    private static final boolean DEBUG_TRIAGED_MISSING = false;
364    private static final boolean DEBUG_APP_DATA = false;
365
366    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
367
368    private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE;
369
370    private static final int RADIO_UID = Process.PHONE_UID;
371    private static final int LOG_UID = Process.LOG_UID;
372    private static final int NFC_UID = Process.NFC_UID;
373    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
374    private static final int SHELL_UID = Process.SHELL_UID;
375
376    // Cap the size of permission trees that 3rd party apps can define
377    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
378
379    // Suffix used during package installation when copying/moving
380    // package apks to install directory.
381    private static final String INSTALL_PACKAGE_SUFFIX = "-";
382
383    static final int SCAN_NO_DEX = 1<<1;
384    static final int SCAN_FORCE_DEX = 1<<2;
385    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
386    static final int SCAN_NEW_INSTALL = 1<<4;
387    static final int SCAN_NO_PATHS = 1<<5;
388    static final int SCAN_UPDATE_TIME = 1<<6;
389    static final int SCAN_DEFER_DEX = 1<<7;
390    static final int SCAN_BOOTING = 1<<8;
391    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
392    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
393    static final int SCAN_REPLACING = 1<<11;
394    static final int SCAN_REQUIRE_KNOWN = 1<<12;
395    static final int SCAN_MOVE = 1<<13;
396    static final int SCAN_INITIAL = 1<<14;
397    static final int SCAN_CHECK_ONLY = 1<<15;
398    static final int SCAN_DONT_KILL_APP = 1<<17;
399    static final int SCAN_IGNORE_FROZEN = 1<<18;
400
401    static final int REMOVE_CHATTY = 1<<16;
402
403    private static final int[] EMPTY_INT_ARRAY = new int[0];
404
405    /**
406     * Timeout (in milliseconds) after which the watchdog should declare that
407     * our handler thread is wedged.  The usual default for such things is one
408     * minute but we sometimes do very lengthy I/O operations on this thread,
409     * such as installing multi-gigabyte applications, so ours needs to be longer.
410     */
411    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
412
413    /**
414     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
415     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
416     * settings entry if available, otherwise we use the hardcoded default.  If it's been
417     * more than this long since the last fstrim, we force one during the boot sequence.
418     *
419     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
420     * one gets run at the next available charging+idle time.  This final mandatory
421     * no-fstrim check kicks in only of the other scheduling criteria is never met.
422     */
423    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
424
425    /**
426     * Whether verification is enabled by default.
427     */
428    private static final boolean DEFAULT_VERIFY_ENABLE = true;
429
430    /**
431     * The default maximum time to wait for the verification agent to return in
432     * milliseconds.
433     */
434    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
435
436    /**
437     * The default response for package verification timeout.
438     *
439     * This can be either PackageManager.VERIFICATION_ALLOW or
440     * PackageManager.VERIFICATION_REJECT.
441     */
442    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
443
444    static final String PLATFORM_PACKAGE_NAME = "android";
445
446    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
447
448    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
449            DEFAULT_CONTAINER_PACKAGE,
450            "com.android.defcontainer.DefaultContainerService");
451
452    private static final String KILL_APP_REASON_GIDS_CHANGED =
453            "permission grant or revoke changed gids";
454
455    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
456            "permissions revoked";
457
458    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
459
460    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
461
462    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
463    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
464
465    /** Permission grant: not grant the permission. */
466    private static final int GRANT_DENIED = 1;
467
468    /** Permission grant: grant the permission as an install permission. */
469    private static final int GRANT_INSTALL = 2;
470
471    /** Permission grant: grant the permission as a runtime one. */
472    private static final int GRANT_RUNTIME = 3;
473
474    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
475    private static final int GRANT_UPGRADE = 4;
476
477    /** Canonical intent used to identify what counts as a "web browser" app */
478    private static final Intent sBrowserIntent;
479    static {
480        sBrowserIntent = new Intent();
481        sBrowserIntent.setAction(Intent.ACTION_VIEW);
482        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
483        sBrowserIntent.setData(Uri.parse("http:"));
484    }
485
486    /**
487     * The set of all protected actions [i.e. those actions for which a high priority
488     * intent filter is disallowed].
489     */
490    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
491    static {
492        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
493        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
494        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
495        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
496    }
497
498    // Compilation reasons.
499    public static final int REASON_FIRST_BOOT = 0;
500    public static final int REASON_BOOT = 1;
501    public static final int REASON_INSTALL = 2;
502    public static final int REASON_BACKGROUND_DEXOPT = 3;
503    public static final int REASON_AB_OTA = 4;
504    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
505    public static final int REASON_SHARED_APK = 6;
506    public static final int REASON_FORCED_DEXOPT = 7;
507    public static final int REASON_CORE_APP = 8;
508
509    public static final int REASON_LAST = REASON_CORE_APP;
510
511    /** Special library name that skips shared libraries check during compilation. */
512    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
513
514    final ServiceThread mHandlerThread;
515
516    final PackageHandler mHandler;
517
518    private final ProcessLoggingHandler mProcessLoggingHandler;
519
520    /**
521     * Messages for {@link #mHandler} that need to wait for system ready before
522     * being dispatched.
523     */
524    private ArrayList<Message> mPostSystemReadyMessages;
525
526    final int mSdkVersion = Build.VERSION.SDK_INT;
527
528    final Context mContext;
529    final boolean mFactoryTest;
530    final boolean mOnlyCore;
531    final DisplayMetrics mMetrics;
532    final int mDefParseFlags;
533    final String[] mSeparateProcesses;
534    final boolean mIsUpgrade;
535    final boolean mIsPreNUpgrade;
536
537    /** The location for ASEC container files on internal storage. */
538    final String mAsecInternalPath;
539
540    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
541    // LOCK HELD.  Can be called with mInstallLock held.
542    @GuardedBy("mInstallLock")
543    final Installer mInstaller;
544
545    /** Directory where installed third-party apps stored */
546    final File mAppInstallDir;
547    final File mEphemeralInstallDir;
548
549    /**
550     * Directory to which applications installed internally have their
551     * 32 bit native libraries copied.
552     */
553    private File mAppLib32InstallDir;
554
555    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
556    // apps.
557    final File mDrmAppPrivateInstallDir;
558
559    // ----------------------------------------------------------------
560
561    // Lock for state used when installing and doing other long running
562    // operations.  Methods that must be called with this lock held have
563    // the suffix "LI".
564    final Object mInstallLock = new Object();
565
566    // ----------------------------------------------------------------
567
568    // Keys are String (package name), values are Package.  This also serves
569    // as the lock for the global state.  Methods that must be called with
570    // this lock held have the prefix "LP".
571    @GuardedBy("mPackages")
572    final ArrayMap<String, PackageParser.Package> mPackages =
573            new ArrayMap<String, PackageParser.Package>();
574
575    final ArrayMap<String, Set<String>> mKnownCodebase =
576            new ArrayMap<String, Set<String>>();
577
578    // Tracks available target package names -> overlay package paths.
579    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
580        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
581
582    /**
583     * Tracks new system packages [received in an OTA] that we expect to
584     * find updated user-installed versions. Keys are package name, values
585     * are package location.
586     */
587    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
588    /**
589     * Tracks high priority intent filters for protected actions. During boot, certain
590     * filter actions are protected and should never be allowed to have a high priority
591     * intent filter for them. However, there is one, and only one exception -- the
592     * setup wizard. It must be able to define a high priority intent filter for these
593     * actions to ensure there are no escapes from the wizard. We need to delay processing
594     * of these during boot as we need to look at all of the system packages in order
595     * to know which component is the setup wizard.
596     */
597    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
598    /**
599     * Whether or not processing protected filters should be deferred.
600     */
601    private boolean mDeferProtectedFilters = true;
602
603    /**
604     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
605     */
606    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
607    /**
608     * Whether or not system app permissions should be promoted from install to runtime.
609     */
610    boolean mPromoteSystemApps;
611
612    @GuardedBy("mPackages")
613    final Settings mSettings;
614
615    /**
616     * Set of package names that are currently "frozen", which means active
617     * surgery is being done on the code/data for that package. The platform
618     * will refuse to launch frozen packages to avoid race conditions.
619     *
620     * @see PackageFreezer
621     */
622    @GuardedBy("mPackages")
623    final ArraySet<String> mFrozenPackages = new ArraySet<>();
624
625    final ProtectedPackages mProtectedPackages;
626
627    boolean mFirstBoot;
628
629    // System configuration read by SystemConfig.
630    final int[] mGlobalGids;
631    final SparseArray<ArraySet<String>> mSystemPermissions;
632    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
633
634    // If mac_permissions.xml was found for seinfo labeling.
635    boolean mFoundPolicyFile;
636
637    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
638
639    public static final class SharedLibraryEntry {
640        public final String path;
641        public final String apk;
642
643        SharedLibraryEntry(String _path, String _apk) {
644            path = _path;
645            apk = _apk;
646        }
647    }
648
649    // Currently known shared libraries.
650    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
651            new ArrayMap<String, SharedLibraryEntry>();
652
653    // All available activities, for your resolving pleasure.
654    final ActivityIntentResolver mActivities =
655            new ActivityIntentResolver();
656
657    // All available receivers, for your resolving pleasure.
658    final ActivityIntentResolver mReceivers =
659            new ActivityIntentResolver();
660
661    // All available services, for your resolving pleasure.
662    final ServiceIntentResolver mServices = new ServiceIntentResolver();
663
664    // All available providers, for your resolving pleasure.
665    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
666
667    // Mapping from provider base names (first directory in content URI codePath)
668    // to the provider information.
669    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
670            new ArrayMap<String, PackageParser.Provider>();
671
672    // Mapping from instrumentation class names to info about them.
673    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
674            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
675
676    // Mapping from permission names to info about them.
677    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
678            new ArrayMap<String, PackageParser.PermissionGroup>();
679
680    // Packages whose data we have transfered into another package, thus
681    // should no longer exist.
682    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
683
684    // Broadcast actions that are only available to the system.
685    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
686
687    /** List of packages waiting for verification. */
688    final SparseArray<PackageVerificationState> mPendingVerification
689            = new SparseArray<PackageVerificationState>();
690
691    /** Set of packages associated with each app op permission. */
692    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
693
694    final PackageInstallerService mInstallerService;
695
696    private final PackageDexOptimizer mPackageDexOptimizer;
697
698    private AtomicInteger mNextMoveId = new AtomicInteger();
699    private final MoveCallbacks mMoveCallbacks;
700
701    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
702
703    // Cache of users who need badging.
704    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
705
706    /** Token for keys in mPendingVerification. */
707    private int mPendingVerificationToken = 0;
708
709    volatile boolean mSystemReady;
710    volatile boolean mSafeMode;
711    volatile boolean mHasSystemUidErrors;
712
713    ApplicationInfo mAndroidApplication;
714    final ActivityInfo mResolveActivity = new ActivityInfo();
715    final ResolveInfo mResolveInfo = new ResolveInfo();
716    ComponentName mResolveComponentName;
717    PackageParser.Package mPlatformPackage;
718    ComponentName mCustomResolverComponentName;
719
720    boolean mResolverReplaced = false;
721
722    private final @Nullable ComponentName mIntentFilterVerifierComponent;
723    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
724
725    private int mIntentFilterVerificationToken = 0;
726
727    /** Component that knows whether or not an ephemeral application exists */
728    final ComponentName mEphemeralResolverComponent;
729    /** The service connection to the ephemeral resolver */
730    final EphemeralResolverConnection mEphemeralResolverConnection;
731
732    /** Component used to install ephemeral applications */
733    final ComponentName mEphemeralInstallerComponent;
734    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
735    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
736
737    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
738            = new SparseArray<IntentFilterVerificationState>();
739
740    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
741            new DefaultPermissionGrantPolicy(this);
742
743    // List of packages names to keep cached, even if they are uninstalled for all users
744    private List<String> mKeepUninstalledPackages;
745
746    private UserManagerInternal mUserManagerInternal;
747
748    private static class IFVerificationParams {
749        PackageParser.Package pkg;
750        boolean replacing;
751        int userId;
752        int verifierUid;
753
754        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
755                int _userId, int _verifierUid) {
756            pkg = _pkg;
757            replacing = _replacing;
758            userId = _userId;
759            replacing = _replacing;
760            verifierUid = _verifierUid;
761        }
762    }
763
764    private interface IntentFilterVerifier<T extends IntentFilter> {
765        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
766                                               T filter, String packageName);
767        void startVerifications(int userId);
768        void receiveVerificationResponse(int verificationId);
769    }
770
771    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
772        private Context mContext;
773        private ComponentName mIntentFilterVerifierComponent;
774        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
775
776        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
777            mContext = context;
778            mIntentFilterVerifierComponent = verifierComponent;
779        }
780
781        private String getDefaultScheme() {
782            return IntentFilter.SCHEME_HTTPS;
783        }
784
785        @Override
786        public void startVerifications(int userId) {
787            // Launch verifications requests
788            int count = mCurrentIntentFilterVerifications.size();
789            for (int n=0; n<count; n++) {
790                int verificationId = mCurrentIntentFilterVerifications.get(n);
791                final IntentFilterVerificationState ivs =
792                        mIntentFilterVerificationStates.get(verificationId);
793
794                String packageName = ivs.getPackageName();
795
796                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
797                final int filterCount = filters.size();
798                ArraySet<String> domainsSet = new ArraySet<>();
799                for (int m=0; m<filterCount; m++) {
800                    PackageParser.ActivityIntentInfo filter = filters.get(m);
801                    domainsSet.addAll(filter.getHostsList());
802                }
803                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
804                synchronized (mPackages) {
805                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
806                            packageName, domainsList) != null) {
807                        scheduleWriteSettingsLocked();
808                    }
809                }
810                sendVerificationRequest(userId, verificationId, ivs);
811            }
812            mCurrentIntentFilterVerifications.clear();
813        }
814
815        private void sendVerificationRequest(int userId, int verificationId,
816                IntentFilterVerificationState ivs) {
817
818            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
819            verificationIntent.putExtra(
820                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
821                    verificationId);
822            verificationIntent.putExtra(
823                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
824                    getDefaultScheme());
825            verificationIntent.putExtra(
826                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
827                    ivs.getHostsString());
828            verificationIntent.putExtra(
829                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
830                    ivs.getPackageName());
831            verificationIntent.setComponent(mIntentFilterVerifierComponent);
832            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
833
834            UserHandle user = new UserHandle(userId);
835            mContext.sendBroadcastAsUser(verificationIntent, user);
836            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
837                    "Sending IntentFilter verification broadcast");
838        }
839
840        public void receiveVerificationResponse(int verificationId) {
841            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
842
843            final boolean verified = ivs.isVerified();
844
845            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
846            final int count = filters.size();
847            if (DEBUG_DOMAIN_VERIFICATION) {
848                Slog.i(TAG, "Received verification response " + verificationId
849                        + " for " + count + " filters, verified=" + verified);
850            }
851            for (int n=0; n<count; n++) {
852                PackageParser.ActivityIntentInfo filter = filters.get(n);
853                filter.setVerified(verified);
854
855                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
856                        + " verified with result:" + verified + " and hosts:"
857                        + ivs.getHostsString());
858            }
859
860            mIntentFilterVerificationStates.remove(verificationId);
861
862            final String packageName = ivs.getPackageName();
863            IntentFilterVerificationInfo ivi = null;
864
865            synchronized (mPackages) {
866                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
867            }
868            if (ivi == null) {
869                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
870                        + verificationId + " packageName:" + packageName);
871                return;
872            }
873            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
874                    "Updating IntentFilterVerificationInfo for package " + packageName
875                            +" verificationId:" + verificationId);
876
877            synchronized (mPackages) {
878                if (verified) {
879                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
880                } else {
881                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
882                }
883                scheduleWriteSettingsLocked();
884
885                final int userId = ivs.getUserId();
886                if (userId != UserHandle.USER_ALL) {
887                    final int userStatus =
888                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
889
890                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
891                    boolean needUpdate = false;
892
893                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
894                    // already been set by the User thru the Disambiguation dialog
895                    switch (userStatus) {
896                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
897                            if (verified) {
898                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
899                            } else {
900                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
901                            }
902                            needUpdate = true;
903                            break;
904
905                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
906                            if (verified) {
907                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
908                                needUpdate = true;
909                            }
910                            break;
911
912                        default:
913                            // Nothing to do
914                    }
915
916                    if (needUpdate) {
917                        mSettings.updateIntentFilterVerificationStatusLPw(
918                                packageName, updatedStatus, userId);
919                        scheduleWritePackageRestrictionsLocked(userId);
920                    }
921                }
922            }
923        }
924
925        @Override
926        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
927                    ActivityIntentInfo filter, String packageName) {
928            if (!hasValidDomains(filter)) {
929                return false;
930            }
931            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
932            if (ivs == null) {
933                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
934                        packageName);
935            }
936            if (DEBUG_DOMAIN_VERIFICATION) {
937                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
938            }
939            ivs.addFilter(filter);
940            return true;
941        }
942
943        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
944                int userId, int verificationId, String packageName) {
945            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
946                    verifierUid, userId, packageName);
947            ivs.setPendingState();
948            synchronized (mPackages) {
949                mIntentFilterVerificationStates.append(verificationId, ivs);
950                mCurrentIntentFilterVerifications.add(verificationId);
951            }
952            return ivs;
953        }
954    }
955
956    private static boolean hasValidDomains(ActivityIntentInfo filter) {
957        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
958                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
959                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
960    }
961
962    // Set of pending broadcasts for aggregating enable/disable of components.
963    static class PendingPackageBroadcasts {
964        // for each user id, a map of <package name -> components within that package>
965        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
966
967        public PendingPackageBroadcasts() {
968            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
969        }
970
971        public ArrayList<String> get(int userId, String packageName) {
972            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
973            return packages.get(packageName);
974        }
975
976        public void put(int userId, String packageName, ArrayList<String> components) {
977            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
978            packages.put(packageName, components);
979        }
980
981        public void remove(int userId, String packageName) {
982            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
983            if (packages != null) {
984                packages.remove(packageName);
985            }
986        }
987
988        public void remove(int userId) {
989            mUidMap.remove(userId);
990        }
991
992        public int userIdCount() {
993            return mUidMap.size();
994        }
995
996        public int userIdAt(int n) {
997            return mUidMap.keyAt(n);
998        }
999
1000        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1001            return mUidMap.get(userId);
1002        }
1003
1004        public int size() {
1005            // total number of pending broadcast entries across all userIds
1006            int num = 0;
1007            for (int i = 0; i< mUidMap.size(); i++) {
1008                num += mUidMap.valueAt(i).size();
1009            }
1010            return num;
1011        }
1012
1013        public void clear() {
1014            mUidMap.clear();
1015        }
1016
1017        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1018            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1019            if (map == null) {
1020                map = new ArrayMap<String, ArrayList<String>>();
1021                mUidMap.put(userId, map);
1022            }
1023            return map;
1024        }
1025    }
1026    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1027
1028    // Service Connection to remote media container service to copy
1029    // package uri's from external media onto secure containers
1030    // or internal storage.
1031    private IMediaContainerService mContainerService = null;
1032
1033    static final int SEND_PENDING_BROADCAST = 1;
1034    static final int MCS_BOUND = 3;
1035    static final int END_COPY = 4;
1036    static final int INIT_COPY = 5;
1037    static final int MCS_UNBIND = 6;
1038    static final int START_CLEANING_PACKAGE = 7;
1039    static final int FIND_INSTALL_LOC = 8;
1040    static final int POST_INSTALL = 9;
1041    static final int MCS_RECONNECT = 10;
1042    static final int MCS_GIVE_UP = 11;
1043    static final int UPDATED_MEDIA_STATUS = 12;
1044    static final int WRITE_SETTINGS = 13;
1045    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1046    static final int PACKAGE_VERIFIED = 15;
1047    static final int CHECK_PENDING_VERIFICATION = 16;
1048    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1049    static final int INTENT_FILTER_VERIFIED = 18;
1050    static final int WRITE_PACKAGE_LIST = 19;
1051
1052    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1053
1054    // Delay time in millisecs
1055    static final int BROADCAST_DELAY = 10 * 1000;
1056
1057    static UserManagerService sUserManager;
1058
1059    // Stores a list of users whose package restrictions file needs to be updated
1060    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1061
1062    final private DefaultContainerConnection mDefContainerConn =
1063            new DefaultContainerConnection();
1064    class DefaultContainerConnection implements ServiceConnection {
1065        public void onServiceConnected(ComponentName name, IBinder service) {
1066            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1067            IMediaContainerService imcs =
1068                IMediaContainerService.Stub.asInterface(service);
1069            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1070        }
1071
1072        public void onServiceDisconnected(ComponentName name) {
1073            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1074        }
1075    }
1076
1077    // Recordkeeping of restore-after-install operations that are currently in flight
1078    // between the Package Manager and the Backup Manager
1079    static class PostInstallData {
1080        public InstallArgs args;
1081        public PackageInstalledInfo res;
1082
1083        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1084            args = _a;
1085            res = _r;
1086        }
1087    }
1088
1089    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1090    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1091
1092    // XML tags for backup/restore of various bits of state
1093    private static final String TAG_PREFERRED_BACKUP = "pa";
1094    private static final String TAG_DEFAULT_APPS = "da";
1095    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1096
1097    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1098    private static final String TAG_ALL_GRANTS = "rt-grants";
1099    private static final String TAG_GRANT = "grant";
1100    private static final String ATTR_PACKAGE_NAME = "pkg";
1101
1102    private static final String TAG_PERMISSION = "perm";
1103    private static final String ATTR_PERMISSION_NAME = "name";
1104    private static final String ATTR_IS_GRANTED = "g";
1105    private static final String ATTR_USER_SET = "set";
1106    private static final String ATTR_USER_FIXED = "fixed";
1107    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1108
1109    // System/policy permission grants are not backed up
1110    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1111            FLAG_PERMISSION_POLICY_FIXED
1112            | FLAG_PERMISSION_SYSTEM_FIXED
1113            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1114
1115    // And we back up these user-adjusted states
1116    private static final int USER_RUNTIME_GRANT_MASK =
1117            FLAG_PERMISSION_USER_SET
1118            | FLAG_PERMISSION_USER_FIXED
1119            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1120
1121    final @Nullable String mRequiredVerifierPackage;
1122    final @NonNull String mRequiredInstallerPackage;
1123    final @Nullable String mSetupWizardPackage;
1124    final @NonNull String mServicesSystemSharedLibraryPackageName;
1125    final @NonNull String mSharedSystemSharedLibraryPackageName;
1126
1127    private final PackageUsage mPackageUsage = new PackageUsage();
1128    private final CompilerStats mCompilerStats = new CompilerStats();
1129
1130    class PackageHandler extends Handler {
1131        private boolean mBound = false;
1132        final ArrayList<HandlerParams> mPendingInstalls =
1133            new ArrayList<HandlerParams>();
1134
1135        private boolean connectToService() {
1136            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1137                    " DefaultContainerService");
1138            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1139            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1140            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1141                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1142                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1143                mBound = true;
1144                return true;
1145            }
1146            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1147            return false;
1148        }
1149
1150        private void disconnectService() {
1151            mContainerService = null;
1152            mBound = false;
1153            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1154            mContext.unbindService(mDefContainerConn);
1155            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1156        }
1157
1158        PackageHandler(Looper looper) {
1159            super(looper);
1160        }
1161
1162        public void handleMessage(Message msg) {
1163            try {
1164                doHandleMessage(msg);
1165            } finally {
1166                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1167            }
1168        }
1169
1170        void doHandleMessage(Message msg) {
1171            switch (msg.what) {
1172                case INIT_COPY: {
1173                    HandlerParams params = (HandlerParams) msg.obj;
1174                    int idx = mPendingInstalls.size();
1175                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1176                    // If a bind was already initiated we dont really
1177                    // need to do anything. The pending install
1178                    // will be processed later on.
1179                    if (!mBound) {
1180                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1181                                System.identityHashCode(mHandler));
1182                        // If this is the only one pending we might
1183                        // have to bind to the service again.
1184                        if (!connectToService()) {
1185                            Slog.e(TAG, "Failed to bind to media container service");
1186                            params.serviceError();
1187                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1188                                    System.identityHashCode(mHandler));
1189                            if (params.traceMethod != null) {
1190                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1191                                        params.traceCookie);
1192                            }
1193                            return;
1194                        } else {
1195                            // Once we bind to the service, the first
1196                            // pending request will be processed.
1197                            mPendingInstalls.add(idx, params);
1198                        }
1199                    } else {
1200                        mPendingInstalls.add(idx, params);
1201                        // Already bound to the service. Just make
1202                        // sure we trigger off processing the first request.
1203                        if (idx == 0) {
1204                            mHandler.sendEmptyMessage(MCS_BOUND);
1205                        }
1206                    }
1207                    break;
1208                }
1209                case MCS_BOUND: {
1210                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1211                    if (msg.obj != null) {
1212                        mContainerService = (IMediaContainerService) msg.obj;
1213                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1214                                System.identityHashCode(mHandler));
1215                    }
1216                    if (mContainerService == null) {
1217                        if (!mBound) {
1218                            // Something seriously wrong since we are not bound and we are not
1219                            // waiting for connection. Bail out.
1220                            Slog.e(TAG, "Cannot bind to media container service");
1221                            for (HandlerParams params : mPendingInstalls) {
1222                                // Indicate service bind error
1223                                params.serviceError();
1224                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1225                                        System.identityHashCode(params));
1226                                if (params.traceMethod != null) {
1227                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1228                                            params.traceMethod, params.traceCookie);
1229                                }
1230                                return;
1231                            }
1232                            mPendingInstalls.clear();
1233                        } else {
1234                            Slog.w(TAG, "Waiting to connect to media container service");
1235                        }
1236                    } else if (mPendingInstalls.size() > 0) {
1237                        HandlerParams params = mPendingInstalls.get(0);
1238                        if (params != null) {
1239                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1240                                    System.identityHashCode(params));
1241                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1242                            if (params.startCopy()) {
1243                                // We are done...  look for more work or to
1244                                // go idle.
1245                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1246                                        "Checking for more work or unbind...");
1247                                // Delete pending install
1248                                if (mPendingInstalls.size() > 0) {
1249                                    mPendingInstalls.remove(0);
1250                                }
1251                                if (mPendingInstalls.size() == 0) {
1252                                    if (mBound) {
1253                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1254                                                "Posting delayed MCS_UNBIND");
1255                                        removeMessages(MCS_UNBIND);
1256                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1257                                        // Unbind after a little delay, to avoid
1258                                        // continual thrashing.
1259                                        sendMessageDelayed(ubmsg, 10000);
1260                                    }
1261                                } else {
1262                                    // There are more pending requests in queue.
1263                                    // Just post MCS_BOUND message to trigger processing
1264                                    // of next pending install.
1265                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1266                                            "Posting MCS_BOUND for next work");
1267                                    mHandler.sendEmptyMessage(MCS_BOUND);
1268                                }
1269                            }
1270                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1271                        }
1272                    } else {
1273                        // Should never happen ideally.
1274                        Slog.w(TAG, "Empty queue");
1275                    }
1276                    break;
1277                }
1278                case MCS_RECONNECT: {
1279                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1280                    if (mPendingInstalls.size() > 0) {
1281                        if (mBound) {
1282                            disconnectService();
1283                        }
1284                        if (!connectToService()) {
1285                            Slog.e(TAG, "Failed to bind to media container service");
1286                            for (HandlerParams params : mPendingInstalls) {
1287                                // Indicate service bind error
1288                                params.serviceError();
1289                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1290                                        System.identityHashCode(params));
1291                            }
1292                            mPendingInstalls.clear();
1293                        }
1294                    }
1295                    break;
1296                }
1297                case MCS_UNBIND: {
1298                    // If there is no actual work left, then time to unbind.
1299                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1300
1301                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1302                        if (mBound) {
1303                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1304
1305                            disconnectService();
1306                        }
1307                    } else if (mPendingInstalls.size() > 0) {
1308                        // There are more pending requests in queue.
1309                        // Just post MCS_BOUND message to trigger processing
1310                        // of next pending install.
1311                        mHandler.sendEmptyMessage(MCS_BOUND);
1312                    }
1313
1314                    break;
1315                }
1316                case MCS_GIVE_UP: {
1317                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1318                    HandlerParams params = mPendingInstalls.remove(0);
1319                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1320                            System.identityHashCode(params));
1321                    break;
1322                }
1323                case SEND_PENDING_BROADCAST: {
1324                    String packages[];
1325                    ArrayList<String> components[];
1326                    int size = 0;
1327                    int uids[];
1328                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1329                    synchronized (mPackages) {
1330                        if (mPendingBroadcasts == null) {
1331                            return;
1332                        }
1333                        size = mPendingBroadcasts.size();
1334                        if (size <= 0) {
1335                            // Nothing to be done. Just return
1336                            return;
1337                        }
1338                        packages = new String[size];
1339                        components = new ArrayList[size];
1340                        uids = new int[size];
1341                        int i = 0;  // filling out the above arrays
1342
1343                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1344                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1345                            Iterator<Map.Entry<String, ArrayList<String>>> it
1346                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1347                                            .entrySet().iterator();
1348                            while (it.hasNext() && i < size) {
1349                                Map.Entry<String, ArrayList<String>> ent = it.next();
1350                                packages[i] = ent.getKey();
1351                                components[i] = ent.getValue();
1352                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1353                                uids[i] = (ps != null)
1354                                        ? UserHandle.getUid(packageUserId, ps.appId)
1355                                        : -1;
1356                                i++;
1357                            }
1358                        }
1359                        size = i;
1360                        mPendingBroadcasts.clear();
1361                    }
1362                    // Send broadcasts
1363                    for (int i = 0; i < size; i++) {
1364                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1365                    }
1366                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1367                    break;
1368                }
1369                case START_CLEANING_PACKAGE: {
1370                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1371                    final String packageName = (String)msg.obj;
1372                    final int userId = msg.arg1;
1373                    final boolean andCode = msg.arg2 != 0;
1374                    synchronized (mPackages) {
1375                        if (userId == UserHandle.USER_ALL) {
1376                            int[] users = sUserManager.getUserIds();
1377                            for (int user : users) {
1378                                mSettings.addPackageToCleanLPw(
1379                                        new PackageCleanItem(user, packageName, andCode));
1380                            }
1381                        } else {
1382                            mSettings.addPackageToCleanLPw(
1383                                    new PackageCleanItem(userId, packageName, andCode));
1384                        }
1385                    }
1386                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1387                    startCleaningPackages();
1388                } break;
1389                case POST_INSTALL: {
1390                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1391
1392                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1393                    final boolean didRestore = (msg.arg2 != 0);
1394                    mRunningInstalls.delete(msg.arg1);
1395
1396                    if (data != null) {
1397                        InstallArgs args = data.args;
1398                        PackageInstalledInfo parentRes = data.res;
1399
1400                        final boolean grantPermissions = (args.installFlags
1401                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1402                        final boolean killApp = (args.installFlags
1403                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1404                        final String[] grantedPermissions = args.installGrantPermissions;
1405
1406                        // Handle the parent package
1407                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1408                                grantedPermissions, didRestore, args.installerPackageName,
1409                                args.observer);
1410
1411                        // Handle the child packages
1412                        final int childCount = (parentRes.addedChildPackages != null)
1413                                ? parentRes.addedChildPackages.size() : 0;
1414                        for (int i = 0; i < childCount; i++) {
1415                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1416                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1417                                    grantedPermissions, false, args.installerPackageName,
1418                                    args.observer);
1419                        }
1420
1421                        // Log tracing if needed
1422                        if (args.traceMethod != null) {
1423                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1424                                    args.traceCookie);
1425                        }
1426                    } else {
1427                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1428                    }
1429
1430                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1431                } break;
1432                case UPDATED_MEDIA_STATUS: {
1433                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1434                    boolean reportStatus = msg.arg1 == 1;
1435                    boolean doGc = msg.arg2 == 1;
1436                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1437                    if (doGc) {
1438                        // Force a gc to clear up stale containers.
1439                        Runtime.getRuntime().gc();
1440                    }
1441                    if (msg.obj != null) {
1442                        @SuppressWarnings("unchecked")
1443                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1444                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1445                        // Unload containers
1446                        unloadAllContainers(args);
1447                    }
1448                    if (reportStatus) {
1449                        try {
1450                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1451                            PackageHelper.getMountService().finishMediaUpdate();
1452                        } catch (RemoteException e) {
1453                            Log.e(TAG, "MountService not running?");
1454                        }
1455                    }
1456                } break;
1457                case WRITE_SETTINGS: {
1458                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1459                    synchronized (mPackages) {
1460                        removeMessages(WRITE_SETTINGS);
1461                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1462                        mSettings.writeLPr();
1463                        mDirtyUsers.clear();
1464                    }
1465                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1466                } break;
1467                case WRITE_PACKAGE_RESTRICTIONS: {
1468                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1469                    synchronized (mPackages) {
1470                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1471                        for (int userId : mDirtyUsers) {
1472                            mSettings.writePackageRestrictionsLPr(userId);
1473                        }
1474                        mDirtyUsers.clear();
1475                    }
1476                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1477                } break;
1478                case WRITE_PACKAGE_LIST: {
1479                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1480                    synchronized (mPackages) {
1481                        removeMessages(WRITE_PACKAGE_LIST);
1482                        mSettings.writePackageListLPr(msg.arg1);
1483                    }
1484                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1485                } break;
1486                case CHECK_PENDING_VERIFICATION: {
1487                    final int verificationId = msg.arg1;
1488                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1489
1490                    if ((state != null) && !state.timeoutExtended()) {
1491                        final InstallArgs args = state.getInstallArgs();
1492                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1493
1494                        Slog.i(TAG, "Verification timed out for " + originUri);
1495                        mPendingVerification.remove(verificationId);
1496
1497                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1498
1499                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1500                            Slog.i(TAG, "Continuing with installation of " + originUri);
1501                            state.setVerifierResponse(Binder.getCallingUid(),
1502                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1503                            broadcastPackageVerified(verificationId, originUri,
1504                                    PackageManager.VERIFICATION_ALLOW,
1505                                    state.getInstallArgs().getUser());
1506                            try {
1507                                ret = args.copyApk(mContainerService, true);
1508                            } catch (RemoteException e) {
1509                                Slog.e(TAG, "Could not contact the ContainerService");
1510                            }
1511                        } else {
1512                            broadcastPackageVerified(verificationId, originUri,
1513                                    PackageManager.VERIFICATION_REJECT,
1514                                    state.getInstallArgs().getUser());
1515                        }
1516
1517                        Trace.asyncTraceEnd(
1518                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1519
1520                        processPendingInstall(args, ret);
1521                        mHandler.sendEmptyMessage(MCS_UNBIND);
1522                    }
1523                    break;
1524                }
1525                case PACKAGE_VERIFIED: {
1526                    final int verificationId = msg.arg1;
1527
1528                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1529                    if (state == null) {
1530                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1531                        break;
1532                    }
1533
1534                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1535
1536                    state.setVerifierResponse(response.callerUid, response.code);
1537
1538                    if (state.isVerificationComplete()) {
1539                        mPendingVerification.remove(verificationId);
1540
1541                        final InstallArgs args = state.getInstallArgs();
1542                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1543
1544                        int ret;
1545                        if (state.isInstallAllowed()) {
1546                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1547                            broadcastPackageVerified(verificationId, originUri,
1548                                    response.code, state.getInstallArgs().getUser());
1549                            try {
1550                                ret = args.copyApk(mContainerService, true);
1551                            } catch (RemoteException e) {
1552                                Slog.e(TAG, "Could not contact the ContainerService");
1553                            }
1554                        } else {
1555                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1556                        }
1557
1558                        Trace.asyncTraceEnd(
1559                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1560
1561                        processPendingInstall(args, ret);
1562                        mHandler.sendEmptyMessage(MCS_UNBIND);
1563                    }
1564
1565                    break;
1566                }
1567                case START_INTENT_FILTER_VERIFICATIONS: {
1568                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1569                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1570                            params.replacing, params.pkg);
1571                    break;
1572                }
1573                case INTENT_FILTER_VERIFIED: {
1574                    final int verificationId = msg.arg1;
1575
1576                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1577                            verificationId);
1578                    if (state == null) {
1579                        Slog.w(TAG, "Invalid IntentFilter verification token "
1580                                + verificationId + " received");
1581                        break;
1582                    }
1583
1584                    final int userId = state.getUserId();
1585
1586                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1587                            "Processing IntentFilter verification with token:"
1588                            + verificationId + " and userId:" + userId);
1589
1590                    final IntentFilterVerificationResponse response =
1591                            (IntentFilterVerificationResponse) msg.obj;
1592
1593                    state.setVerifierResponse(response.callerUid, response.code);
1594
1595                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1596                            "IntentFilter verification with token:" + verificationId
1597                            + " and userId:" + userId
1598                            + " is settings verifier response with response code:"
1599                            + response.code);
1600
1601                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1602                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1603                                + response.getFailedDomainsString());
1604                    }
1605
1606                    if (state.isVerificationComplete()) {
1607                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1608                    } else {
1609                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1610                                "IntentFilter verification with token:" + verificationId
1611                                + " was not said to be complete");
1612                    }
1613
1614                    break;
1615                }
1616            }
1617        }
1618    }
1619
1620    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1621            boolean killApp, String[] grantedPermissions,
1622            boolean launchedForRestore, String installerPackage,
1623            IPackageInstallObserver2 installObserver) {
1624        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1625            // Send the removed broadcasts
1626            if (res.removedInfo != null) {
1627                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1628            }
1629
1630            // Now that we successfully installed the package, grant runtime
1631            // permissions if requested before broadcasting the install.
1632            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1633                    >= Build.VERSION_CODES.M) {
1634                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1635            }
1636
1637            final boolean update = res.removedInfo != null
1638                    && res.removedInfo.removedPackage != null;
1639
1640            // If this is the first time we have child packages for a disabled privileged
1641            // app that had no children, we grant requested runtime permissions to the new
1642            // children if the parent on the system image had them already granted.
1643            if (res.pkg.parentPackage != null) {
1644                synchronized (mPackages) {
1645                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1646                }
1647            }
1648
1649            synchronized (mPackages) {
1650                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1651            }
1652
1653            final String packageName = res.pkg.applicationInfo.packageName;
1654            Bundle extras = new Bundle(1);
1655            extras.putInt(Intent.EXTRA_UID, res.uid);
1656
1657            // Determine the set of users who are adding this package for
1658            // the first time vs. those who are seeing an update.
1659            int[] firstUsers = EMPTY_INT_ARRAY;
1660            int[] updateUsers = EMPTY_INT_ARRAY;
1661            if (res.origUsers == null || res.origUsers.length == 0) {
1662                firstUsers = res.newUsers;
1663            } else {
1664                for (int newUser : res.newUsers) {
1665                    boolean isNew = true;
1666                    for (int origUser : res.origUsers) {
1667                        if (origUser == newUser) {
1668                            isNew = false;
1669                            break;
1670                        }
1671                    }
1672                    if (isNew) {
1673                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1674                    } else {
1675                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1676                    }
1677                }
1678            }
1679
1680            // Send installed broadcasts if the install/update is not ephemeral
1681            if (!isEphemeral(res.pkg)) {
1682                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1683
1684                // Send added for users that see the package for the first time
1685                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1686                        extras, 0 /*flags*/, null /*targetPackage*/,
1687                        null /*finishedReceiver*/, firstUsers);
1688
1689                // Send added for users that don't see the package for the first time
1690                if (update) {
1691                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1692                }
1693                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1694                        extras, 0 /*flags*/, null /*targetPackage*/,
1695                        null /*finishedReceiver*/, updateUsers);
1696
1697                // Send replaced for users that don't see the package for the first time
1698                if (update) {
1699                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1700                            packageName, extras, 0 /*flags*/,
1701                            null /*targetPackage*/, null /*finishedReceiver*/,
1702                            updateUsers);
1703                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1704                            null /*package*/, null /*extras*/, 0 /*flags*/,
1705                            packageName /*targetPackage*/,
1706                            null /*finishedReceiver*/, updateUsers);
1707                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1708                    // First-install and we did a restore, so we're responsible for the
1709                    // first-launch broadcast.
1710                    if (DEBUG_BACKUP) {
1711                        Slog.i(TAG, "Post-restore of " + packageName
1712                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1713                    }
1714                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1715                }
1716
1717                // Send broadcast package appeared if forward locked/external for all users
1718                // treat asec-hosted packages like removable media on upgrade
1719                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1720                    if (DEBUG_INSTALL) {
1721                        Slog.i(TAG, "upgrading pkg " + res.pkg
1722                                + " is ASEC-hosted -> AVAILABLE");
1723                    }
1724                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1725                    ArrayList<String> pkgList = new ArrayList<>(1);
1726                    pkgList.add(packageName);
1727                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1728                }
1729            }
1730
1731            // Work that needs to happen on first install within each user
1732            if (firstUsers != null && firstUsers.length > 0) {
1733                synchronized (mPackages) {
1734                    for (int userId : firstUsers) {
1735                        // If this app is a browser and it's newly-installed for some
1736                        // users, clear any default-browser state in those users. The
1737                        // app's nature doesn't depend on the user, so we can just check
1738                        // its browser nature in any user and generalize.
1739                        if (packageIsBrowser(packageName, userId)) {
1740                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1741                        }
1742
1743                        // We may also need to apply pending (restored) runtime
1744                        // permission grants within these users.
1745                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1746                    }
1747                }
1748            }
1749
1750            // Log current value of "unknown sources" setting
1751            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1752                    getUnknownSourcesSettings());
1753
1754            // Force a gc to clear up things
1755            Runtime.getRuntime().gc();
1756
1757            // Remove the replaced package's older resources safely now
1758            // We delete after a gc for applications  on sdcard.
1759            if (res.removedInfo != null && res.removedInfo.args != null) {
1760                synchronized (mInstallLock) {
1761                    res.removedInfo.args.doPostDeleteLI(true);
1762                }
1763            }
1764        }
1765
1766        // If someone is watching installs - notify them
1767        if (installObserver != null) {
1768            try {
1769                Bundle extras = extrasForInstallResult(res);
1770                installObserver.onPackageInstalled(res.name, res.returnCode,
1771                        res.returnMsg, extras);
1772            } catch (RemoteException e) {
1773                Slog.i(TAG, "Observer no longer exists.");
1774            }
1775        }
1776    }
1777
1778    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1779            PackageParser.Package pkg) {
1780        if (pkg.parentPackage == null) {
1781            return;
1782        }
1783        if (pkg.requestedPermissions == null) {
1784            return;
1785        }
1786        final PackageSetting disabledSysParentPs = mSettings
1787                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1788        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1789                || !disabledSysParentPs.isPrivileged()
1790                || (disabledSysParentPs.childPackageNames != null
1791                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1792            return;
1793        }
1794        final int[] allUserIds = sUserManager.getUserIds();
1795        final int permCount = pkg.requestedPermissions.size();
1796        for (int i = 0; i < permCount; i++) {
1797            String permission = pkg.requestedPermissions.get(i);
1798            BasePermission bp = mSettings.mPermissions.get(permission);
1799            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1800                continue;
1801            }
1802            for (int userId : allUserIds) {
1803                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1804                        permission, userId)) {
1805                    grantRuntimePermission(pkg.packageName, permission, userId);
1806                }
1807            }
1808        }
1809    }
1810
1811    private StorageEventListener mStorageListener = new StorageEventListener() {
1812        @Override
1813        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1814            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1815                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1816                    final String volumeUuid = vol.getFsUuid();
1817
1818                    // Clean up any users or apps that were removed or recreated
1819                    // while this volume was missing
1820                    reconcileUsers(volumeUuid);
1821                    reconcileApps(volumeUuid);
1822
1823                    // Clean up any install sessions that expired or were
1824                    // cancelled while this volume was missing
1825                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1826
1827                    loadPrivatePackages(vol);
1828
1829                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1830                    unloadPrivatePackages(vol);
1831                }
1832            }
1833
1834            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1835                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1836                    updateExternalMediaStatus(true, false);
1837                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1838                    updateExternalMediaStatus(false, false);
1839                }
1840            }
1841        }
1842
1843        @Override
1844        public void onVolumeForgotten(String fsUuid) {
1845            if (TextUtils.isEmpty(fsUuid)) {
1846                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1847                return;
1848            }
1849
1850            // Remove any apps installed on the forgotten volume
1851            synchronized (mPackages) {
1852                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1853                for (PackageSetting ps : packages) {
1854                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1855                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1856                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1857                }
1858
1859                mSettings.onVolumeForgotten(fsUuid);
1860                mSettings.writeLPr();
1861            }
1862        }
1863    };
1864
1865    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1866            String[] grantedPermissions) {
1867        for (int userId : userIds) {
1868            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1869        }
1870
1871        // We could have touched GID membership, so flush out packages.list
1872        synchronized (mPackages) {
1873            mSettings.writePackageListLPr();
1874        }
1875    }
1876
1877    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1878            String[] grantedPermissions) {
1879        SettingBase sb = (SettingBase) pkg.mExtras;
1880        if (sb == null) {
1881            return;
1882        }
1883
1884        PermissionsState permissionsState = sb.getPermissionsState();
1885
1886        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1887                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1888
1889        for (String permission : pkg.requestedPermissions) {
1890            final BasePermission bp;
1891            synchronized (mPackages) {
1892                bp = mSettings.mPermissions.get(permission);
1893            }
1894            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1895                    && (grantedPermissions == null
1896                           || ArrayUtils.contains(grantedPermissions, permission))) {
1897                final int flags = permissionsState.getPermissionFlags(permission, userId);
1898                // Installer cannot change immutable permissions.
1899                if ((flags & immutableFlags) == 0) {
1900                    grantRuntimePermission(pkg.packageName, permission, userId);
1901                }
1902            }
1903        }
1904    }
1905
1906    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1907        Bundle extras = null;
1908        switch (res.returnCode) {
1909            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1910                extras = new Bundle();
1911                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1912                        res.origPermission);
1913                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1914                        res.origPackage);
1915                break;
1916            }
1917            case PackageManager.INSTALL_SUCCEEDED: {
1918                extras = new Bundle();
1919                extras.putBoolean(Intent.EXTRA_REPLACING,
1920                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1921                break;
1922            }
1923        }
1924        return extras;
1925    }
1926
1927    void scheduleWriteSettingsLocked() {
1928        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1929            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1930        }
1931    }
1932
1933    void scheduleWritePackageListLocked(int userId) {
1934        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1935            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1936            msg.arg1 = userId;
1937            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1938        }
1939    }
1940
1941    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1942        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1943        scheduleWritePackageRestrictionsLocked(userId);
1944    }
1945
1946    void scheduleWritePackageRestrictionsLocked(int userId) {
1947        final int[] userIds = (userId == UserHandle.USER_ALL)
1948                ? sUserManager.getUserIds() : new int[]{userId};
1949        for (int nextUserId : userIds) {
1950            if (!sUserManager.exists(nextUserId)) return;
1951            mDirtyUsers.add(nextUserId);
1952            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1953                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1954            }
1955        }
1956    }
1957
1958    public static PackageManagerService main(Context context, Installer installer,
1959            boolean factoryTest, boolean onlyCore) {
1960        // Self-check for initial settings.
1961        PackageManagerServiceCompilerMapping.checkProperties();
1962
1963        PackageManagerService m = new PackageManagerService(context, installer,
1964                factoryTest, onlyCore);
1965        m.enableSystemUserPackages();
1966        ServiceManager.addService("package", m);
1967        return m;
1968    }
1969
1970    private void enableSystemUserPackages() {
1971        if (!UserManager.isSplitSystemUser()) {
1972            return;
1973        }
1974        // For system user, enable apps based on the following conditions:
1975        // - app is whitelisted or belong to one of these groups:
1976        //   -- system app which has no launcher icons
1977        //   -- system app which has INTERACT_ACROSS_USERS permission
1978        //   -- system IME app
1979        // - app is not in the blacklist
1980        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1981        Set<String> enableApps = new ArraySet<>();
1982        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1983                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1984                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1985        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1986        enableApps.addAll(wlApps);
1987        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1988                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1989        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1990        enableApps.removeAll(blApps);
1991        Log.i(TAG, "Applications installed for system user: " + enableApps);
1992        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1993                UserHandle.SYSTEM);
1994        final int allAppsSize = allAps.size();
1995        synchronized (mPackages) {
1996            for (int i = 0; i < allAppsSize; i++) {
1997                String pName = allAps.get(i);
1998                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1999                // Should not happen, but we shouldn't be failing if it does
2000                if (pkgSetting == null) {
2001                    continue;
2002                }
2003                boolean install = enableApps.contains(pName);
2004                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2005                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2006                            + " for system user");
2007                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2008                }
2009            }
2010        }
2011    }
2012
2013    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2014        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2015                Context.DISPLAY_SERVICE);
2016        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2017    }
2018
2019    /**
2020     * Requests that files preopted on a secondary system partition be copied to the data partition
2021     * if possible.  Note that the actual copying of the files is accomplished by init for security
2022     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2023     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2024     */
2025    private static void requestCopyPreoptedFiles() {
2026        final int WAIT_TIME_MS = 100;
2027        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2028        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2029            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2030            // We will wait for up to 100 seconds.
2031            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2032            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2033                try {
2034                    Thread.sleep(WAIT_TIME_MS);
2035                } catch (InterruptedException e) {
2036                    // Do nothing
2037                }
2038                if (SystemClock.uptimeMillis() > timeEnd) {
2039                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2040                    Slog.wtf(TAG, "cppreopt did not finish!");
2041                    break;
2042                }
2043            }
2044        }
2045    }
2046
2047    public PackageManagerService(Context context, Installer installer,
2048            boolean factoryTest, boolean onlyCore) {
2049        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2050                SystemClock.uptimeMillis());
2051
2052        if (mSdkVersion <= 0) {
2053            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2054        }
2055
2056        mContext = context;
2057        mFactoryTest = factoryTest;
2058        mOnlyCore = onlyCore;
2059        mMetrics = new DisplayMetrics();
2060        mSettings = new Settings(mPackages);
2061        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2062                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2063        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2064                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2065        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2066                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2067        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2068                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2069        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2070                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2071        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2072                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2073
2074        String separateProcesses = SystemProperties.get("debug.separate_processes");
2075        if (separateProcesses != null && separateProcesses.length() > 0) {
2076            if ("*".equals(separateProcesses)) {
2077                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2078                mSeparateProcesses = null;
2079                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2080            } else {
2081                mDefParseFlags = 0;
2082                mSeparateProcesses = separateProcesses.split(",");
2083                Slog.w(TAG, "Running with debug.separate_processes: "
2084                        + separateProcesses);
2085            }
2086        } else {
2087            mDefParseFlags = 0;
2088            mSeparateProcesses = null;
2089        }
2090
2091        mInstaller = installer;
2092        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2093                "*dexopt*");
2094        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2095
2096        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2097                FgThread.get().getLooper());
2098
2099        getDefaultDisplayMetrics(context, mMetrics);
2100
2101        SystemConfig systemConfig = SystemConfig.getInstance();
2102        mGlobalGids = systemConfig.getGlobalGids();
2103        mSystemPermissions = systemConfig.getSystemPermissions();
2104        mAvailableFeatures = systemConfig.getAvailableFeatures();
2105
2106        mProtectedPackages = new ProtectedPackages(mContext);
2107
2108        synchronized (mInstallLock) {
2109        // writer
2110        synchronized (mPackages) {
2111            mHandlerThread = new ServiceThread(TAG,
2112                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2113            mHandlerThread.start();
2114            mHandler = new PackageHandler(mHandlerThread.getLooper());
2115            mProcessLoggingHandler = new ProcessLoggingHandler();
2116            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2117
2118            File dataDir = Environment.getDataDirectory();
2119            mAppInstallDir = new File(dataDir, "app");
2120            mAppLib32InstallDir = new File(dataDir, "app-lib");
2121            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2122            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2123            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2124
2125            sUserManager = new UserManagerService(context, this, mPackages);
2126
2127            // Propagate permission configuration in to package manager.
2128            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2129                    = systemConfig.getPermissions();
2130            for (int i=0; i<permConfig.size(); i++) {
2131                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2132                BasePermission bp = mSettings.mPermissions.get(perm.name);
2133                if (bp == null) {
2134                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2135                    mSettings.mPermissions.put(perm.name, bp);
2136                }
2137                if (perm.gids != null) {
2138                    bp.setGids(perm.gids, perm.perUser);
2139                }
2140            }
2141
2142            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2143            for (int i=0; i<libConfig.size(); i++) {
2144                mSharedLibraries.put(libConfig.keyAt(i),
2145                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2146            }
2147
2148            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2149
2150            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2151
2152            if (mFirstBoot) {
2153                requestCopyPreoptedFiles();
2154            }
2155
2156            String customResolverActivity = Resources.getSystem().getString(
2157                    R.string.config_customResolverActivity);
2158            if (TextUtils.isEmpty(customResolverActivity)) {
2159                customResolverActivity = null;
2160            } else {
2161                mCustomResolverComponentName = ComponentName.unflattenFromString(
2162                        customResolverActivity);
2163            }
2164
2165            long startTime = SystemClock.uptimeMillis();
2166
2167            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2168                    startTime);
2169
2170            // Set flag to monitor and not change apk file paths when
2171            // scanning install directories.
2172            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2173
2174            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2175            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2176
2177            if (bootClassPath == null) {
2178                Slog.w(TAG, "No BOOTCLASSPATH found!");
2179            }
2180
2181            if (systemServerClassPath == null) {
2182                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2183            }
2184
2185            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2186            final String[] dexCodeInstructionSets =
2187                    getDexCodeInstructionSets(
2188                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2189
2190            /**
2191             * Ensure all external libraries have had dexopt run on them.
2192             */
2193            if (mSharedLibraries.size() > 0) {
2194                // NOTE: For now, we're compiling these system "shared libraries"
2195                // (and framework jars) into all available architectures. It's possible
2196                // to compile them only when we come across an app that uses them (there's
2197                // already logic for that in scanPackageLI) but that adds some complexity.
2198                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2199                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2200                        final String lib = libEntry.path;
2201                        if (lib == null) {
2202                            continue;
2203                        }
2204
2205                        try {
2206                            // Shared libraries do not have profiles so we perform a full
2207                            // AOT compilation (if needed).
2208                            int dexoptNeeded = DexFile.getDexOptNeeded(
2209                                    lib, dexCodeInstructionSet,
2210                                    getCompilerFilterForReason(REASON_SHARED_APK),
2211                                    false /* newProfile */);
2212                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2213                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2214                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2215                                        getCompilerFilterForReason(REASON_SHARED_APK),
2216                                        StorageManager.UUID_PRIVATE_INTERNAL,
2217                                        SKIP_SHARED_LIBRARY_CHECK);
2218                            }
2219                        } catch (FileNotFoundException e) {
2220                            Slog.w(TAG, "Library not found: " + lib);
2221                        } catch (IOException | InstallerException e) {
2222                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2223                                    + e.getMessage());
2224                        }
2225                    }
2226                }
2227            }
2228
2229            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2230
2231            final VersionInfo ver = mSettings.getInternalVersion();
2232            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2233
2234            // when upgrading from pre-M, promote system app permissions from install to runtime
2235            mPromoteSystemApps =
2236                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2237
2238            // When upgrading from pre-N, we need to handle package extraction like first boot,
2239            // as there is no profiling data available.
2240            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2241
2242            // save off the names of pre-existing system packages prior to scanning; we don't
2243            // want to automatically grant runtime permissions for new system apps
2244            if (mPromoteSystemApps) {
2245                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2246                while (pkgSettingIter.hasNext()) {
2247                    PackageSetting ps = pkgSettingIter.next();
2248                    if (isSystemApp(ps)) {
2249                        mExistingSystemPackages.add(ps.name);
2250                    }
2251                }
2252            }
2253
2254            // Collect vendor overlay packages.
2255            // (Do this before scanning any apps.)
2256            // For security and version matching reason, only consider
2257            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2258            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2259            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2260                    | PackageParser.PARSE_IS_SYSTEM
2261                    | PackageParser.PARSE_IS_SYSTEM_DIR
2262                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2263
2264            // Find base frameworks (resource packages without code).
2265            scanDirTracedLI(frameworkDir, mDefParseFlags
2266                    | PackageParser.PARSE_IS_SYSTEM
2267                    | PackageParser.PARSE_IS_SYSTEM_DIR
2268                    | PackageParser.PARSE_IS_PRIVILEGED,
2269                    scanFlags | SCAN_NO_DEX, 0);
2270
2271            // Collected privileged system packages.
2272            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2273            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2274                    | PackageParser.PARSE_IS_SYSTEM
2275                    | PackageParser.PARSE_IS_SYSTEM_DIR
2276                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2277
2278            // Collect ordinary system packages.
2279            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2280            scanDirTracedLI(systemAppDir, mDefParseFlags
2281                    | PackageParser.PARSE_IS_SYSTEM
2282                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2283
2284            // Collect all vendor packages.
2285            File vendorAppDir = new File("/vendor/app");
2286            try {
2287                vendorAppDir = vendorAppDir.getCanonicalFile();
2288            } catch (IOException e) {
2289                // failed to look up canonical path, continue with original one
2290            }
2291            scanDirTracedLI(vendorAppDir, mDefParseFlags
2292                    | PackageParser.PARSE_IS_SYSTEM
2293                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2294
2295            // Collect all OEM packages.
2296            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2297            scanDirTracedLI(oemAppDir, mDefParseFlags
2298                    | PackageParser.PARSE_IS_SYSTEM
2299                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2300
2301            // Prune any system packages that no longer exist.
2302            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2303            if (!mOnlyCore) {
2304                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2305                while (psit.hasNext()) {
2306                    PackageSetting ps = psit.next();
2307
2308                    /*
2309                     * If this is not a system app, it can't be a
2310                     * disable system app.
2311                     */
2312                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2313                        continue;
2314                    }
2315
2316                    /*
2317                     * If the package is scanned, it's not erased.
2318                     */
2319                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2320                    if (scannedPkg != null) {
2321                        /*
2322                         * If the system app is both scanned and in the
2323                         * disabled packages list, then it must have been
2324                         * added via OTA. Remove it from the currently
2325                         * scanned package so the previously user-installed
2326                         * application can be scanned.
2327                         */
2328                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2329                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2330                                    + ps.name + "; removing system app.  Last known codePath="
2331                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2332                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2333                                    + scannedPkg.mVersionCode);
2334                            removePackageLI(scannedPkg, true);
2335                            mExpectingBetter.put(ps.name, ps.codePath);
2336                        }
2337
2338                        continue;
2339                    }
2340
2341                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2342                        psit.remove();
2343                        logCriticalInfo(Log.WARN, "System package " + ps.name
2344                                + " no longer exists; it's data will be wiped");
2345                        // Actual deletion of code and data will be handled by later
2346                        // reconciliation step
2347                    } else {
2348                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2349                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2350                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2351                        }
2352                    }
2353                }
2354            }
2355
2356            //look for any incomplete package installations
2357            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2358            for (int i = 0; i < deletePkgsList.size(); i++) {
2359                // Actual deletion of code and data will be handled by later
2360                // reconciliation step
2361                final String packageName = deletePkgsList.get(i).name;
2362                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2363                synchronized (mPackages) {
2364                    mSettings.removePackageLPw(packageName);
2365                }
2366            }
2367
2368            //delete tmp files
2369            deleteTempPackageFiles();
2370
2371            // Remove any shared userIDs that have no associated packages
2372            mSettings.pruneSharedUsersLPw();
2373
2374            if (!mOnlyCore) {
2375                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2376                        SystemClock.uptimeMillis());
2377                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2378
2379                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2380                        | PackageParser.PARSE_FORWARD_LOCK,
2381                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2382
2383                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2384                        | PackageParser.PARSE_IS_EPHEMERAL,
2385                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2386
2387                /**
2388                 * Remove disable package settings for any updated system
2389                 * apps that were removed via an OTA. If they're not a
2390                 * previously-updated app, remove them completely.
2391                 * Otherwise, just revoke their system-level permissions.
2392                 */
2393                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2394                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2395                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2396
2397                    String msg;
2398                    if (deletedPkg == null) {
2399                        msg = "Updated system package " + deletedAppName
2400                                + " no longer exists; it's data will be wiped";
2401                        // Actual deletion of code and data will be handled by later
2402                        // reconciliation step
2403                    } else {
2404                        msg = "Updated system app + " + deletedAppName
2405                                + " no longer present; removing system privileges for "
2406                                + deletedAppName;
2407
2408                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2409
2410                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2411                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2412                    }
2413                    logCriticalInfo(Log.WARN, msg);
2414                }
2415
2416                /**
2417                 * Make sure all system apps that we expected to appear on
2418                 * the userdata partition actually showed up. If they never
2419                 * appeared, crawl back and revive the system version.
2420                 */
2421                for (int i = 0; i < mExpectingBetter.size(); i++) {
2422                    final String packageName = mExpectingBetter.keyAt(i);
2423                    if (!mPackages.containsKey(packageName)) {
2424                        final File scanFile = mExpectingBetter.valueAt(i);
2425
2426                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2427                                + " but never showed up; reverting to system");
2428
2429                        int reparseFlags = mDefParseFlags;
2430                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2431                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2432                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2433                                    | PackageParser.PARSE_IS_PRIVILEGED;
2434                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2435                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2436                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2437                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2438                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2439                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2440                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2441                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2442                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2443                        } else {
2444                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2445                            continue;
2446                        }
2447
2448                        mSettings.enableSystemPackageLPw(packageName);
2449
2450                        try {
2451                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2452                        } catch (PackageManagerException e) {
2453                            Slog.e(TAG, "Failed to parse original system package: "
2454                                    + e.getMessage());
2455                        }
2456                    }
2457                }
2458            }
2459            mExpectingBetter.clear();
2460
2461            // Resolve protected action filters. Only the setup wizard is allowed to
2462            // have a high priority filter for these actions.
2463            mSetupWizardPackage = getSetupWizardPackageName();
2464            if (mProtectedFilters.size() > 0) {
2465                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2466                    Slog.i(TAG, "No setup wizard;"
2467                        + " All protected intents capped to priority 0");
2468                }
2469                for (ActivityIntentInfo filter : mProtectedFilters) {
2470                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2471                        if (DEBUG_FILTERS) {
2472                            Slog.i(TAG, "Found setup wizard;"
2473                                + " allow priority " + filter.getPriority() + ";"
2474                                + " package: " + filter.activity.info.packageName
2475                                + " activity: " + filter.activity.className
2476                                + " priority: " + filter.getPriority());
2477                        }
2478                        // skip setup wizard; allow it to keep the high priority filter
2479                        continue;
2480                    }
2481                    Slog.w(TAG, "Protected action; cap priority to 0;"
2482                            + " package: " + filter.activity.info.packageName
2483                            + " activity: " + filter.activity.className
2484                            + " origPrio: " + filter.getPriority());
2485                    filter.setPriority(0);
2486                }
2487            }
2488            mDeferProtectedFilters = false;
2489            mProtectedFilters.clear();
2490
2491            // Now that we know all of the shared libraries, update all clients to have
2492            // the correct library paths.
2493            updateAllSharedLibrariesLPw();
2494
2495            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2496                // NOTE: We ignore potential failures here during a system scan (like
2497                // the rest of the commands above) because there's precious little we
2498                // can do about it. A settings error is reported, though.
2499                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2500                        false /* boot complete */);
2501            }
2502
2503            // Now that we know all the packages we are keeping,
2504            // read and update their last usage times.
2505            mPackageUsage.read(mPackages);
2506            mCompilerStats.read();
2507
2508            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2509                    SystemClock.uptimeMillis());
2510            Slog.i(TAG, "Time to scan packages: "
2511                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2512                    + " seconds");
2513
2514            // If the platform SDK has changed since the last time we booted,
2515            // we need to re-grant app permission to catch any new ones that
2516            // appear.  This is really a hack, and means that apps can in some
2517            // cases get permissions that the user didn't initially explicitly
2518            // allow...  it would be nice to have some better way to handle
2519            // this situation.
2520            int updateFlags = UPDATE_PERMISSIONS_ALL;
2521            if (ver.sdkVersion != mSdkVersion) {
2522                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2523                        + mSdkVersion + "; regranting permissions for internal storage");
2524                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2525            }
2526            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2527            ver.sdkVersion = mSdkVersion;
2528
2529            // If this is the first boot or an update from pre-M, and it is a normal
2530            // boot, then we need to initialize the default preferred apps across
2531            // all defined users.
2532            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2533                for (UserInfo user : sUserManager.getUsers(true)) {
2534                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2535                    applyFactoryDefaultBrowserLPw(user.id);
2536                    primeDomainVerificationsLPw(user.id);
2537                }
2538            }
2539
2540            // Prepare storage for system user really early during boot,
2541            // since core system apps like SettingsProvider and SystemUI
2542            // can't wait for user to start
2543            final int storageFlags;
2544            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2545                storageFlags = StorageManager.FLAG_STORAGE_DE;
2546            } else {
2547                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2548            }
2549            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2550                    storageFlags);
2551
2552            // If this is first boot after an OTA, and a normal boot, then
2553            // we need to clear code cache directories.
2554            // Note that we do *not* clear the application profiles. These remain valid
2555            // across OTAs and are used to drive profile verification (post OTA) and
2556            // profile compilation (without waiting to collect a fresh set of profiles).
2557            if (mIsUpgrade && !onlyCore) {
2558                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2559                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2560                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2561                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2562                        // No apps are running this early, so no need to freeze
2563                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2564                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2565                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2566                    }
2567                }
2568                ver.fingerprint = Build.FINGERPRINT;
2569            }
2570
2571            checkDefaultBrowser();
2572
2573            // clear only after permissions and other defaults have been updated
2574            mExistingSystemPackages.clear();
2575            mPromoteSystemApps = false;
2576
2577            // All the changes are done during package scanning.
2578            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2579
2580            // can downgrade to reader
2581            mSettings.writeLPr();
2582
2583            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2584            // early on (before the package manager declares itself as early) because other
2585            // components in the system server might ask for package contexts for these apps.
2586            //
2587            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2588            // (i.e, that the data partition is unavailable).
2589            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2590                long start = System.nanoTime();
2591                List<PackageParser.Package> coreApps = new ArrayList<>();
2592                for (PackageParser.Package pkg : mPackages.values()) {
2593                    if (pkg.coreApp) {
2594                        coreApps.add(pkg);
2595                    }
2596                }
2597
2598                int[] stats = performDexOptUpgrade(coreApps, false,
2599                        getCompilerFilterForReason(REASON_CORE_APP));
2600
2601                final int elapsedTimeSeconds =
2602                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2603                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2604
2605                if (DEBUG_DEXOPT) {
2606                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2607                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2608                }
2609
2610
2611                // TODO: Should we log these stats to tron too ?
2612                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2613                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2614                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2615                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2616            }
2617
2618            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2619                    SystemClock.uptimeMillis());
2620
2621            if (!mOnlyCore) {
2622                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2623                mRequiredInstallerPackage = getRequiredInstallerLPr();
2624                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2625                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2626                        mIntentFilterVerifierComponent);
2627                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2628                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2629                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2630                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2631            } else {
2632                mRequiredVerifierPackage = null;
2633                mRequiredInstallerPackage = null;
2634                mIntentFilterVerifierComponent = null;
2635                mIntentFilterVerifier = null;
2636                mServicesSystemSharedLibraryPackageName = null;
2637                mSharedSystemSharedLibraryPackageName = null;
2638            }
2639
2640            mInstallerService = new PackageInstallerService(context, this);
2641
2642            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2643            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2644            // both the installer and resolver must be present to enable ephemeral
2645            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2646                if (DEBUG_EPHEMERAL) {
2647                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2648                            + " installer:" + ephemeralInstallerComponent);
2649                }
2650                mEphemeralResolverComponent = ephemeralResolverComponent;
2651                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2652                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2653                mEphemeralResolverConnection =
2654                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2655            } else {
2656                if (DEBUG_EPHEMERAL) {
2657                    final String missingComponent =
2658                            (ephemeralResolverComponent == null)
2659                            ? (ephemeralInstallerComponent == null)
2660                                    ? "resolver and installer"
2661                                    : "resolver"
2662                            : "installer";
2663                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2664                }
2665                mEphemeralResolverComponent = null;
2666                mEphemeralInstallerComponent = null;
2667                mEphemeralResolverConnection = null;
2668            }
2669
2670            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2671        } // synchronized (mPackages)
2672        } // synchronized (mInstallLock)
2673
2674        // Now after opening every single application zip, make sure they
2675        // are all flushed.  Not really needed, but keeps things nice and
2676        // tidy.
2677        Runtime.getRuntime().gc();
2678
2679        // The initial scanning above does many calls into installd while
2680        // holding the mPackages lock, but we're mostly interested in yelling
2681        // once we have a booted system.
2682        mInstaller.setWarnIfHeld(mPackages);
2683
2684        // Expose private service for system components to use.
2685        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2686    }
2687
2688    @Override
2689    public boolean isFirstBoot() {
2690        return mFirstBoot;
2691    }
2692
2693    @Override
2694    public boolean isOnlyCoreApps() {
2695        return mOnlyCore;
2696    }
2697
2698    @Override
2699    public boolean isUpgrade() {
2700        return mIsUpgrade;
2701    }
2702
2703    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2704        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2705
2706        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2707                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2708                UserHandle.USER_SYSTEM);
2709        if (matches.size() == 1) {
2710            return matches.get(0).getComponentInfo().packageName;
2711        } else {
2712            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2713            return null;
2714        }
2715    }
2716
2717    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2718        synchronized (mPackages) {
2719            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2720            if (libraryEntry == null) {
2721                throw new IllegalStateException("Missing required shared library:" + libraryName);
2722            }
2723            return libraryEntry.apk;
2724        }
2725    }
2726
2727    private @NonNull String getRequiredInstallerLPr() {
2728        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2729        intent.addCategory(Intent.CATEGORY_DEFAULT);
2730        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2731
2732        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2733                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2734                UserHandle.USER_SYSTEM);
2735        if (matches.size() == 1) {
2736            ResolveInfo resolveInfo = matches.get(0);
2737            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2738                throw new RuntimeException("The installer must be a privileged app");
2739            }
2740            return matches.get(0).getComponentInfo().packageName;
2741        } else {
2742            throw new RuntimeException("There must be exactly one installer; found " + matches);
2743        }
2744    }
2745
2746    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2747        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2748
2749        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2750                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2751                UserHandle.USER_SYSTEM);
2752        ResolveInfo best = null;
2753        final int N = matches.size();
2754        for (int i = 0; i < N; i++) {
2755            final ResolveInfo cur = matches.get(i);
2756            final String packageName = cur.getComponentInfo().packageName;
2757            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2758                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2759                continue;
2760            }
2761
2762            if (best == null || cur.priority > best.priority) {
2763                best = cur;
2764            }
2765        }
2766
2767        if (best != null) {
2768            return best.getComponentInfo().getComponentName();
2769        } else {
2770            throw new RuntimeException("There must be at least one intent filter verifier");
2771        }
2772    }
2773
2774    private @Nullable ComponentName getEphemeralResolverLPr() {
2775        final String[] packageArray =
2776                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2777        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2778            if (DEBUG_EPHEMERAL) {
2779                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2780            }
2781            return null;
2782        }
2783
2784        final int resolveFlags =
2785                MATCH_DIRECT_BOOT_AWARE
2786                | MATCH_DIRECT_BOOT_UNAWARE
2787                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2788        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2789        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2790                resolveFlags, UserHandle.USER_SYSTEM);
2791
2792        final int N = resolvers.size();
2793        if (N == 0) {
2794            if (DEBUG_EPHEMERAL) {
2795                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2796            }
2797            return null;
2798        }
2799
2800        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2801        for (int i = 0; i < N; i++) {
2802            final ResolveInfo info = resolvers.get(i);
2803
2804            if (info.serviceInfo == null) {
2805                continue;
2806            }
2807
2808            final String packageName = info.serviceInfo.packageName;
2809            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2810                if (DEBUG_EPHEMERAL) {
2811                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2812                            + " pkg: " + packageName + ", info:" + info);
2813                }
2814                continue;
2815            }
2816
2817            if (DEBUG_EPHEMERAL) {
2818                Slog.v(TAG, "Ephemeral resolver found;"
2819                        + " pkg: " + packageName + ", info:" + info);
2820            }
2821            return new ComponentName(packageName, info.serviceInfo.name);
2822        }
2823        if (DEBUG_EPHEMERAL) {
2824            Slog.v(TAG, "Ephemeral resolver NOT found");
2825        }
2826        return null;
2827    }
2828
2829    private @Nullable ComponentName getEphemeralInstallerLPr() {
2830        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2831        intent.addCategory(Intent.CATEGORY_DEFAULT);
2832        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2833
2834        final int resolveFlags =
2835                MATCH_DIRECT_BOOT_AWARE
2836                | MATCH_DIRECT_BOOT_UNAWARE
2837                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2838        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2839                resolveFlags, UserHandle.USER_SYSTEM);
2840        if (matches.size() == 0) {
2841            return null;
2842        } else if (matches.size() == 1) {
2843            return matches.get(0).getComponentInfo().getComponentName();
2844        } else {
2845            throw new RuntimeException(
2846                    "There must be at most one ephemeral installer; found " + matches);
2847        }
2848    }
2849
2850    private void primeDomainVerificationsLPw(int userId) {
2851        if (DEBUG_DOMAIN_VERIFICATION) {
2852            Slog.d(TAG, "Priming domain verifications in user " + userId);
2853        }
2854
2855        SystemConfig systemConfig = SystemConfig.getInstance();
2856        ArraySet<String> packages = systemConfig.getLinkedApps();
2857        ArraySet<String> domains = new ArraySet<String>();
2858
2859        for (String packageName : packages) {
2860            PackageParser.Package pkg = mPackages.get(packageName);
2861            if (pkg != null) {
2862                if (!pkg.isSystemApp()) {
2863                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2864                    continue;
2865                }
2866
2867                domains.clear();
2868                for (PackageParser.Activity a : pkg.activities) {
2869                    for (ActivityIntentInfo filter : a.intents) {
2870                        if (hasValidDomains(filter)) {
2871                            domains.addAll(filter.getHostsList());
2872                        }
2873                    }
2874                }
2875
2876                if (domains.size() > 0) {
2877                    if (DEBUG_DOMAIN_VERIFICATION) {
2878                        Slog.v(TAG, "      + " + packageName);
2879                    }
2880                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2881                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2882                    // and then 'always' in the per-user state actually used for intent resolution.
2883                    final IntentFilterVerificationInfo ivi;
2884                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2885                            new ArrayList<String>(domains));
2886                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2887                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2888                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2889                } else {
2890                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2891                            + "' does not handle web links");
2892                }
2893            } else {
2894                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2895            }
2896        }
2897
2898        scheduleWritePackageRestrictionsLocked(userId);
2899        scheduleWriteSettingsLocked();
2900    }
2901
2902    private void applyFactoryDefaultBrowserLPw(int userId) {
2903        // The default browser app's package name is stored in a string resource,
2904        // with a product-specific overlay used for vendor customization.
2905        String browserPkg = mContext.getResources().getString(
2906                com.android.internal.R.string.default_browser);
2907        if (!TextUtils.isEmpty(browserPkg)) {
2908            // non-empty string => required to be a known package
2909            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2910            if (ps == null) {
2911                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2912                browserPkg = null;
2913            } else {
2914                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2915            }
2916        }
2917
2918        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2919        // default.  If there's more than one, just leave everything alone.
2920        if (browserPkg == null) {
2921            calculateDefaultBrowserLPw(userId);
2922        }
2923    }
2924
2925    private void calculateDefaultBrowserLPw(int userId) {
2926        List<String> allBrowsers = resolveAllBrowserApps(userId);
2927        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2928        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2929    }
2930
2931    private List<String> resolveAllBrowserApps(int userId) {
2932        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2933        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2934                PackageManager.MATCH_ALL, userId);
2935
2936        final int count = list.size();
2937        List<String> result = new ArrayList<String>(count);
2938        for (int i=0; i<count; i++) {
2939            ResolveInfo info = list.get(i);
2940            if (info.activityInfo == null
2941                    || !info.handleAllWebDataURI
2942                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2943                    || result.contains(info.activityInfo.packageName)) {
2944                continue;
2945            }
2946            result.add(info.activityInfo.packageName);
2947        }
2948
2949        return result;
2950    }
2951
2952    private boolean packageIsBrowser(String packageName, int userId) {
2953        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2954                PackageManager.MATCH_ALL, userId);
2955        final int N = list.size();
2956        for (int i = 0; i < N; i++) {
2957            ResolveInfo info = list.get(i);
2958            if (packageName.equals(info.activityInfo.packageName)) {
2959                return true;
2960            }
2961        }
2962        return false;
2963    }
2964
2965    private void checkDefaultBrowser() {
2966        final int myUserId = UserHandle.myUserId();
2967        final String packageName = getDefaultBrowserPackageName(myUserId);
2968        if (packageName != null) {
2969            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2970            if (info == null) {
2971                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2972                synchronized (mPackages) {
2973                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2974                }
2975            }
2976        }
2977    }
2978
2979    @Override
2980    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2981            throws RemoteException {
2982        try {
2983            return super.onTransact(code, data, reply, flags);
2984        } catch (RuntimeException e) {
2985            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2986                Slog.wtf(TAG, "Package Manager Crash", e);
2987            }
2988            throw e;
2989        }
2990    }
2991
2992    static int[] appendInts(int[] cur, int[] add) {
2993        if (add == null) return cur;
2994        if (cur == null) return add;
2995        final int N = add.length;
2996        for (int i=0; i<N; i++) {
2997            cur = appendInt(cur, add[i]);
2998        }
2999        return cur;
3000    }
3001
3002    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3003        if (!sUserManager.exists(userId)) return null;
3004        if (ps == null) {
3005            return null;
3006        }
3007        final PackageParser.Package p = ps.pkg;
3008        if (p == null) {
3009            return null;
3010        }
3011
3012        final PermissionsState permissionsState = ps.getPermissionsState();
3013
3014        // Compute GIDs only if requested
3015        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3016                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3017        // Compute granted permissions only if package has requested permissions
3018        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3019                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3020        final PackageUserState state = ps.readUserState(userId);
3021
3022        return PackageParser.generatePackageInfo(p, gids, flags,
3023                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3024    }
3025
3026    @Override
3027    public void checkPackageStartable(String packageName, int userId) {
3028        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3029
3030        synchronized (mPackages) {
3031            final PackageSetting ps = mSettings.mPackages.get(packageName);
3032            if (ps == null) {
3033                throw new SecurityException("Package " + packageName + " was not found!");
3034            }
3035
3036            if (!ps.getInstalled(userId)) {
3037                throw new SecurityException(
3038                        "Package " + packageName + " was not installed for user " + userId + "!");
3039            }
3040
3041            if (mSafeMode && !ps.isSystem()) {
3042                throw new SecurityException("Package " + packageName + " not a system app!");
3043            }
3044
3045            if (mFrozenPackages.contains(packageName)) {
3046                throw new SecurityException("Package " + packageName + " is currently frozen!");
3047            }
3048
3049            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3050                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3051                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3052            }
3053        }
3054    }
3055
3056    @Override
3057    public boolean isPackageAvailable(String packageName, int userId) {
3058        if (!sUserManager.exists(userId)) return false;
3059        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3060                false /* requireFullPermission */, false /* checkShell */, "is package available");
3061        synchronized (mPackages) {
3062            PackageParser.Package p = mPackages.get(packageName);
3063            if (p != null) {
3064                final PackageSetting ps = (PackageSetting) p.mExtras;
3065                if (ps != null) {
3066                    final PackageUserState state = ps.readUserState(userId);
3067                    if (state != null) {
3068                        return PackageParser.isAvailable(state);
3069                    }
3070                }
3071            }
3072        }
3073        return false;
3074    }
3075
3076    @Override
3077    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3078        if (!sUserManager.exists(userId)) return null;
3079        flags = updateFlagsForPackage(flags, userId, packageName);
3080        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3081                false /* requireFullPermission */, false /* checkShell */, "get package info");
3082        // reader
3083        synchronized (mPackages) {
3084            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3085            PackageParser.Package p = null;
3086            if (matchFactoryOnly) {
3087                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3088                if (ps != null) {
3089                    return generatePackageInfo(ps, flags, userId);
3090                }
3091            }
3092            if (p == null) {
3093                p = mPackages.get(packageName);
3094                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3095                    return null;
3096                }
3097            }
3098            if (DEBUG_PACKAGE_INFO)
3099                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3100            if (p != null) {
3101                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3102            }
3103            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3104                final PackageSetting ps = mSettings.mPackages.get(packageName);
3105                return generatePackageInfo(ps, flags, userId);
3106            }
3107        }
3108        return null;
3109    }
3110
3111    @Override
3112    public String[] currentToCanonicalPackageNames(String[] names) {
3113        String[] out = new String[names.length];
3114        // reader
3115        synchronized (mPackages) {
3116            for (int i=names.length-1; i>=0; i--) {
3117                PackageSetting ps = mSettings.mPackages.get(names[i]);
3118                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3119            }
3120        }
3121        return out;
3122    }
3123
3124    @Override
3125    public String[] canonicalToCurrentPackageNames(String[] names) {
3126        String[] out = new String[names.length];
3127        // reader
3128        synchronized (mPackages) {
3129            for (int i=names.length-1; i>=0; i--) {
3130                String cur = mSettings.mRenamedPackages.get(names[i]);
3131                out[i] = cur != null ? cur : names[i];
3132            }
3133        }
3134        return out;
3135    }
3136
3137    @Override
3138    public int getPackageUid(String packageName, int flags, int userId) {
3139        if (!sUserManager.exists(userId)) return -1;
3140        flags = updateFlagsForPackage(flags, userId, packageName);
3141        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3142                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3143
3144        // reader
3145        synchronized (mPackages) {
3146            final PackageParser.Package p = mPackages.get(packageName);
3147            if (p != null && p.isMatch(flags)) {
3148                return UserHandle.getUid(userId, p.applicationInfo.uid);
3149            }
3150            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3151                final PackageSetting ps = mSettings.mPackages.get(packageName);
3152                if (ps != null && ps.isMatch(flags)) {
3153                    return UserHandle.getUid(userId, ps.appId);
3154                }
3155            }
3156        }
3157
3158        return -1;
3159    }
3160
3161    @Override
3162    public int[] getPackageGids(String packageName, int flags, int userId) {
3163        if (!sUserManager.exists(userId)) return null;
3164        flags = updateFlagsForPackage(flags, userId, packageName);
3165        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3166                false /* requireFullPermission */, false /* checkShell */,
3167                "getPackageGids");
3168
3169        // reader
3170        synchronized (mPackages) {
3171            final PackageParser.Package p = mPackages.get(packageName);
3172            if (p != null && p.isMatch(flags)) {
3173                PackageSetting ps = (PackageSetting) p.mExtras;
3174                return ps.getPermissionsState().computeGids(userId);
3175            }
3176            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3177                final PackageSetting ps = mSettings.mPackages.get(packageName);
3178                if (ps != null && ps.isMatch(flags)) {
3179                    return ps.getPermissionsState().computeGids(userId);
3180                }
3181            }
3182        }
3183
3184        return null;
3185    }
3186
3187    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3188        if (bp.perm != null) {
3189            return PackageParser.generatePermissionInfo(bp.perm, flags);
3190        }
3191        PermissionInfo pi = new PermissionInfo();
3192        pi.name = bp.name;
3193        pi.packageName = bp.sourcePackage;
3194        pi.nonLocalizedLabel = bp.name;
3195        pi.protectionLevel = bp.protectionLevel;
3196        return pi;
3197    }
3198
3199    @Override
3200    public PermissionInfo getPermissionInfo(String name, int flags) {
3201        // reader
3202        synchronized (mPackages) {
3203            final BasePermission p = mSettings.mPermissions.get(name);
3204            if (p != null) {
3205                return generatePermissionInfo(p, flags);
3206            }
3207            return null;
3208        }
3209    }
3210
3211    @Override
3212    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3213            int flags) {
3214        // reader
3215        synchronized (mPackages) {
3216            if (group != null && !mPermissionGroups.containsKey(group)) {
3217                // This is thrown as NameNotFoundException
3218                return null;
3219            }
3220
3221            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3222            for (BasePermission p : mSettings.mPermissions.values()) {
3223                if (group == null) {
3224                    if (p.perm == null || p.perm.info.group == null) {
3225                        out.add(generatePermissionInfo(p, flags));
3226                    }
3227                } else {
3228                    if (p.perm != null && group.equals(p.perm.info.group)) {
3229                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3230                    }
3231                }
3232            }
3233            return new ParceledListSlice<>(out);
3234        }
3235    }
3236
3237    @Override
3238    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3239        // reader
3240        synchronized (mPackages) {
3241            return PackageParser.generatePermissionGroupInfo(
3242                    mPermissionGroups.get(name), flags);
3243        }
3244    }
3245
3246    @Override
3247    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3248        // reader
3249        synchronized (mPackages) {
3250            final int N = mPermissionGroups.size();
3251            ArrayList<PermissionGroupInfo> out
3252                    = new ArrayList<PermissionGroupInfo>(N);
3253            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3254                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3255            }
3256            return new ParceledListSlice<>(out);
3257        }
3258    }
3259
3260    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3261            int userId) {
3262        if (!sUserManager.exists(userId)) return null;
3263        PackageSetting ps = mSettings.mPackages.get(packageName);
3264        if (ps != null) {
3265            if (ps.pkg == null) {
3266                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3267                if (pInfo != null) {
3268                    return pInfo.applicationInfo;
3269                }
3270                return null;
3271            }
3272            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3273                    ps.readUserState(userId), userId);
3274        }
3275        return null;
3276    }
3277
3278    @Override
3279    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3280        if (!sUserManager.exists(userId)) return null;
3281        flags = updateFlagsForApplication(flags, userId, packageName);
3282        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3283                false /* requireFullPermission */, false /* checkShell */, "get application info");
3284        // writer
3285        synchronized (mPackages) {
3286            PackageParser.Package p = mPackages.get(packageName);
3287            if (DEBUG_PACKAGE_INFO) Log.v(
3288                    TAG, "getApplicationInfo " + packageName
3289                    + ": " + p);
3290            if (p != null) {
3291                PackageSetting ps = mSettings.mPackages.get(packageName);
3292                if (ps == null) return null;
3293                // Note: isEnabledLP() does not apply here - always return info
3294                return PackageParser.generateApplicationInfo(
3295                        p, flags, ps.readUserState(userId), userId);
3296            }
3297            if ("android".equals(packageName)||"system".equals(packageName)) {
3298                return mAndroidApplication;
3299            }
3300            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3301                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3302            }
3303        }
3304        return null;
3305    }
3306
3307    @Override
3308    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3309            final IPackageDataObserver observer) {
3310        mContext.enforceCallingOrSelfPermission(
3311                android.Manifest.permission.CLEAR_APP_CACHE, null);
3312        // Queue up an async operation since clearing cache may take a little while.
3313        mHandler.post(new Runnable() {
3314            public void run() {
3315                mHandler.removeCallbacks(this);
3316                boolean success = true;
3317                synchronized (mInstallLock) {
3318                    try {
3319                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3320                    } catch (InstallerException e) {
3321                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3322                        success = false;
3323                    }
3324                }
3325                if (observer != null) {
3326                    try {
3327                        observer.onRemoveCompleted(null, success);
3328                    } catch (RemoteException e) {
3329                        Slog.w(TAG, "RemoveException when invoking call back");
3330                    }
3331                }
3332            }
3333        });
3334    }
3335
3336    @Override
3337    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3338            final IntentSender pi) {
3339        mContext.enforceCallingOrSelfPermission(
3340                android.Manifest.permission.CLEAR_APP_CACHE, null);
3341        // Queue up an async operation since clearing cache may take a little while.
3342        mHandler.post(new Runnable() {
3343            public void run() {
3344                mHandler.removeCallbacks(this);
3345                boolean success = true;
3346                synchronized (mInstallLock) {
3347                    try {
3348                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3349                    } catch (InstallerException e) {
3350                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3351                        success = false;
3352                    }
3353                }
3354                if(pi != null) {
3355                    try {
3356                        // Callback via pending intent
3357                        int code = success ? 1 : 0;
3358                        pi.sendIntent(null, code, null,
3359                                null, null);
3360                    } catch (SendIntentException e1) {
3361                        Slog.i(TAG, "Failed to send pending intent");
3362                    }
3363                }
3364            }
3365        });
3366    }
3367
3368    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3369        synchronized (mInstallLock) {
3370            try {
3371                mInstaller.freeCache(volumeUuid, freeStorageSize);
3372            } catch (InstallerException e) {
3373                throw new IOException("Failed to free enough space", e);
3374            }
3375        }
3376    }
3377
3378    /**
3379     * Update given flags based on encryption status of current user.
3380     */
3381    private int updateFlags(int flags, int userId) {
3382        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3383                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3384            // Caller expressed an explicit opinion about what encryption
3385            // aware/unaware components they want to see, so fall through and
3386            // give them what they want
3387        } else {
3388            // Caller expressed no opinion, so match based on user state
3389            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3390                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3391            } else {
3392                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3393            }
3394        }
3395        return flags;
3396    }
3397
3398    private UserManagerInternal getUserManagerInternal() {
3399        if (mUserManagerInternal == null) {
3400            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3401        }
3402        return mUserManagerInternal;
3403    }
3404
3405    /**
3406     * Update given flags when being used to request {@link PackageInfo}.
3407     */
3408    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3409        boolean triaged = true;
3410        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3411                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3412            // Caller is asking for component details, so they'd better be
3413            // asking for specific encryption matching behavior, or be triaged
3414            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3415                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3416                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3417                triaged = false;
3418            }
3419        }
3420        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3421                | PackageManager.MATCH_SYSTEM_ONLY
3422                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3423            triaged = false;
3424        }
3425        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3426            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3427                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3428        }
3429        return updateFlags(flags, userId);
3430    }
3431
3432    /**
3433     * Update given flags when being used to request {@link ApplicationInfo}.
3434     */
3435    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3436        return updateFlagsForPackage(flags, userId, cookie);
3437    }
3438
3439    /**
3440     * Update given flags when being used to request {@link ComponentInfo}.
3441     */
3442    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3443        if (cookie instanceof Intent) {
3444            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3445                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3446            }
3447        }
3448
3449        boolean triaged = true;
3450        // Caller is asking for component details, so they'd better be
3451        // asking for specific encryption matching behavior, or be triaged
3452        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3453                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3454                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3455            triaged = false;
3456        }
3457        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3458            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3459                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3460        }
3461
3462        return updateFlags(flags, userId);
3463    }
3464
3465    /**
3466     * Update given flags when being used to request {@link ResolveInfo}.
3467     */
3468    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3469        // Safe mode means we shouldn't match any third-party components
3470        if (mSafeMode) {
3471            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3472        }
3473
3474        return updateFlagsForComponent(flags, userId, cookie);
3475    }
3476
3477    @Override
3478    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3479        if (!sUserManager.exists(userId)) return null;
3480        flags = updateFlagsForComponent(flags, userId, component);
3481        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3482                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3483        synchronized (mPackages) {
3484            PackageParser.Activity a = mActivities.mActivities.get(component);
3485
3486            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3487            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3488                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3489                if (ps == null) return null;
3490                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3491                        userId);
3492            }
3493            if (mResolveComponentName.equals(component)) {
3494                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3495                        new PackageUserState(), userId);
3496            }
3497        }
3498        return null;
3499    }
3500
3501    @Override
3502    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3503            String resolvedType) {
3504        synchronized (mPackages) {
3505            if (component.equals(mResolveComponentName)) {
3506                // The resolver supports EVERYTHING!
3507                return true;
3508            }
3509            PackageParser.Activity a = mActivities.mActivities.get(component);
3510            if (a == null) {
3511                return false;
3512            }
3513            for (int i=0; i<a.intents.size(); i++) {
3514                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3515                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3516                    return true;
3517                }
3518            }
3519            return false;
3520        }
3521    }
3522
3523    @Override
3524    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3525        if (!sUserManager.exists(userId)) return null;
3526        flags = updateFlagsForComponent(flags, userId, component);
3527        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3528                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3529        synchronized (mPackages) {
3530            PackageParser.Activity a = mReceivers.mActivities.get(component);
3531            if (DEBUG_PACKAGE_INFO) Log.v(
3532                TAG, "getReceiverInfo " + component + ": " + a);
3533            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3534                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3535                if (ps == null) return null;
3536                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3537                        userId);
3538            }
3539        }
3540        return null;
3541    }
3542
3543    @Override
3544    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3545        if (!sUserManager.exists(userId)) return null;
3546        flags = updateFlagsForComponent(flags, userId, component);
3547        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3548                false /* requireFullPermission */, false /* checkShell */, "get service info");
3549        synchronized (mPackages) {
3550            PackageParser.Service s = mServices.mServices.get(component);
3551            if (DEBUG_PACKAGE_INFO) Log.v(
3552                TAG, "getServiceInfo " + component + ": " + s);
3553            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3554                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3555                if (ps == null) return null;
3556                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3557                        userId);
3558            }
3559        }
3560        return null;
3561    }
3562
3563    @Override
3564    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3565        if (!sUserManager.exists(userId)) return null;
3566        flags = updateFlagsForComponent(flags, userId, component);
3567        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3568                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3569        synchronized (mPackages) {
3570            PackageParser.Provider p = mProviders.mProviders.get(component);
3571            if (DEBUG_PACKAGE_INFO) Log.v(
3572                TAG, "getProviderInfo " + component + ": " + p);
3573            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3574                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3575                if (ps == null) return null;
3576                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3577                        userId);
3578            }
3579        }
3580        return null;
3581    }
3582
3583    @Override
3584    public String[] getSystemSharedLibraryNames() {
3585        Set<String> libSet;
3586        synchronized (mPackages) {
3587            libSet = mSharedLibraries.keySet();
3588            int size = libSet.size();
3589            if (size > 0) {
3590                String[] libs = new String[size];
3591                libSet.toArray(libs);
3592                return libs;
3593            }
3594        }
3595        return null;
3596    }
3597
3598    @Override
3599    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3600        synchronized (mPackages) {
3601            return mServicesSystemSharedLibraryPackageName;
3602        }
3603    }
3604
3605    @Override
3606    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3607        synchronized (mPackages) {
3608            return mSharedSystemSharedLibraryPackageName;
3609        }
3610    }
3611
3612    @Override
3613    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3614        synchronized (mPackages) {
3615            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3616
3617            final FeatureInfo fi = new FeatureInfo();
3618            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3619                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3620            res.add(fi);
3621
3622            return new ParceledListSlice<>(res);
3623        }
3624    }
3625
3626    @Override
3627    public boolean hasSystemFeature(String name, int version) {
3628        synchronized (mPackages) {
3629            final FeatureInfo feat = mAvailableFeatures.get(name);
3630            if (feat == null) {
3631                return false;
3632            } else {
3633                return feat.version >= version;
3634            }
3635        }
3636    }
3637
3638    @Override
3639    public int checkPermission(String permName, String pkgName, int userId) {
3640        if (!sUserManager.exists(userId)) {
3641            return PackageManager.PERMISSION_DENIED;
3642        }
3643
3644        synchronized (mPackages) {
3645            final PackageParser.Package p = mPackages.get(pkgName);
3646            if (p != null && p.mExtras != null) {
3647                final PackageSetting ps = (PackageSetting) p.mExtras;
3648                final PermissionsState permissionsState = ps.getPermissionsState();
3649                if (permissionsState.hasPermission(permName, userId)) {
3650                    return PackageManager.PERMISSION_GRANTED;
3651                }
3652                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3653                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3654                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3655                    return PackageManager.PERMISSION_GRANTED;
3656                }
3657            }
3658        }
3659
3660        return PackageManager.PERMISSION_DENIED;
3661    }
3662
3663    @Override
3664    public int checkUidPermission(String permName, int uid) {
3665        final int userId = UserHandle.getUserId(uid);
3666
3667        if (!sUserManager.exists(userId)) {
3668            return PackageManager.PERMISSION_DENIED;
3669        }
3670
3671        synchronized (mPackages) {
3672            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3673            if (obj != null) {
3674                final SettingBase ps = (SettingBase) obj;
3675                final PermissionsState permissionsState = ps.getPermissionsState();
3676                if (permissionsState.hasPermission(permName, userId)) {
3677                    return PackageManager.PERMISSION_GRANTED;
3678                }
3679                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3680                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3681                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3682                    return PackageManager.PERMISSION_GRANTED;
3683                }
3684            } else {
3685                ArraySet<String> perms = mSystemPermissions.get(uid);
3686                if (perms != null) {
3687                    if (perms.contains(permName)) {
3688                        return PackageManager.PERMISSION_GRANTED;
3689                    }
3690                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3691                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3692                        return PackageManager.PERMISSION_GRANTED;
3693                    }
3694                }
3695            }
3696        }
3697
3698        return PackageManager.PERMISSION_DENIED;
3699    }
3700
3701    @Override
3702    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3703        if (UserHandle.getCallingUserId() != userId) {
3704            mContext.enforceCallingPermission(
3705                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3706                    "isPermissionRevokedByPolicy for user " + userId);
3707        }
3708
3709        if (checkPermission(permission, packageName, userId)
3710                == PackageManager.PERMISSION_GRANTED) {
3711            return false;
3712        }
3713
3714        final long identity = Binder.clearCallingIdentity();
3715        try {
3716            final int flags = getPermissionFlags(permission, packageName, userId);
3717            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3718        } finally {
3719            Binder.restoreCallingIdentity(identity);
3720        }
3721    }
3722
3723    @Override
3724    public String getPermissionControllerPackageName() {
3725        synchronized (mPackages) {
3726            return mRequiredInstallerPackage;
3727        }
3728    }
3729
3730    /**
3731     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3732     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3733     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3734     * @param message the message to log on security exception
3735     */
3736    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3737            boolean checkShell, String message) {
3738        if (userId < 0) {
3739            throw new IllegalArgumentException("Invalid userId " + userId);
3740        }
3741        if (checkShell) {
3742            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3743        }
3744        if (userId == UserHandle.getUserId(callingUid)) return;
3745        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3746            if (requireFullPermission) {
3747                mContext.enforceCallingOrSelfPermission(
3748                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3749            } else {
3750                try {
3751                    mContext.enforceCallingOrSelfPermission(
3752                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3753                } catch (SecurityException se) {
3754                    mContext.enforceCallingOrSelfPermission(
3755                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3756                }
3757            }
3758        }
3759    }
3760
3761    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3762        if (callingUid == Process.SHELL_UID) {
3763            if (userHandle >= 0
3764                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3765                throw new SecurityException("Shell does not have permission to access user "
3766                        + userHandle);
3767            } else if (userHandle < 0) {
3768                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3769                        + Debug.getCallers(3));
3770            }
3771        }
3772    }
3773
3774    private BasePermission findPermissionTreeLP(String permName) {
3775        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3776            if (permName.startsWith(bp.name) &&
3777                    permName.length() > bp.name.length() &&
3778                    permName.charAt(bp.name.length()) == '.') {
3779                return bp;
3780            }
3781        }
3782        return null;
3783    }
3784
3785    private BasePermission checkPermissionTreeLP(String permName) {
3786        if (permName != null) {
3787            BasePermission bp = findPermissionTreeLP(permName);
3788            if (bp != null) {
3789                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3790                    return bp;
3791                }
3792                throw new SecurityException("Calling uid "
3793                        + Binder.getCallingUid()
3794                        + " is not allowed to add to permission tree "
3795                        + bp.name + " owned by uid " + bp.uid);
3796            }
3797        }
3798        throw new SecurityException("No permission tree found for " + permName);
3799    }
3800
3801    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3802        if (s1 == null) {
3803            return s2 == null;
3804        }
3805        if (s2 == null) {
3806            return false;
3807        }
3808        if (s1.getClass() != s2.getClass()) {
3809            return false;
3810        }
3811        return s1.equals(s2);
3812    }
3813
3814    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3815        if (pi1.icon != pi2.icon) return false;
3816        if (pi1.logo != pi2.logo) return false;
3817        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3818        if (!compareStrings(pi1.name, pi2.name)) return false;
3819        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3820        // We'll take care of setting this one.
3821        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3822        // These are not currently stored in settings.
3823        //if (!compareStrings(pi1.group, pi2.group)) return false;
3824        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3825        //if (pi1.labelRes != pi2.labelRes) return false;
3826        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3827        return true;
3828    }
3829
3830    int permissionInfoFootprint(PermissionInfo info) {
3831        int size = info.name.length();
3832        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3833        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3834        return size;
3835    }
3836
3837    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3838        int size = 0;
3839        for (BasePermission perm : mSettings.mPermissions.values()) {
3840            if (perm.uid == tree.uid) {
3841                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3842            }
3843        }
3844        return size;
3845    }
3846
3847    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3848        // We calculate the max size of permissions defined by this uid and throw
3849        // if that plus the size of 'info' would exceed our stated maximum.
3850        if (tree.uid != Process.SYSTEM_UID) {
3851            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3852            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3853                throw new SecurityException("Permission tree size cap exceeded");
3854            }
3855        }
3856    }
3857
3858    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3859        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3860            throw new SecurityException("Label must be specified in permission");
3861        }
3862        BasePermission tree = checkPermissionTreeLP(info.name);
3863        BasePermission bp = mSettings.mPermissions.get(info.name);
3864        boolean added = bp == null;
3865        boolean changed = true;
3866        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3867        if (added) {
3868            enforcePermissionCapLocked(info, tree);
3869            bp = new BasePermission(info.name, tree.sourcePackage,
3870                    BasePermission.TYPE_DYNAMIC);
3871        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3872            throw new SecurityException(
3873                    "Not allowed to modify non-dynamic permission "
3874                    + info.name);
3875        } else {
3876            if (bp.protectionLevel == fixedLevel
3877                    && bp.perm.owner.equals(tree.perm.owner)
3878                    && bp.uid == tree.uid
3879                    && comparePermissionInfos(bp.perm.info, info)) {
3880                changed = false;
3881            }
3882        }
3883        bp.protectionLevel = fixedLevel;
3884        info = new PermissionInfo(info);
3885        info.protectionLevel = fixedLevel;
3886        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3887        bp.perm.info.packageName = tree.perm.info.packageName;
3888        bp.uid = tree.uid;
3889        if (added) {
3890            mSettings.mPermissions.put(info.name, bp);
3891        }
3892        if (changed) {
3893            if (!async) {
3894                mSettings.writeLPr();
3895            } else {
3896                scheduleWriteSettingsLocked();
3897            }
3898        }
3899        return added;
3900    }
3901
3902    @Override
3903    public boolean addPermission(PermissionInfo info) {
3904        synchronized (mPackages) {
3905            return addPermissionLocked(info, false);
3906        }
3907    }
3908
3909    @Override
3910    public boolean addPermissionAsync(PermissionInfo info) {
3911        synchronized (mPackages) {
3912            return addPermissionLocked(info, true);
3913        }
3914    }
3915
3916    @Override
3917    public void removePermission(String name) {
3918        synchronized (mPackages) {
3919            checkPermissionTreeLP(name);
3920            BasePermission bp = mSettings.mPermissions.get(name);
3921            if (bp != null) {
3922                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3923                    throw new SecurityException(
3924                            "Not allowed to modify non-dynamic permission "
3925                            + name);
3926                }
3927                mSettings.mPermissions.remove(name);
3928                mSettings.writeLPr();
3929            }
3930        }
3931    }
3932
3933    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3934            BasePermission bp) {
3935        int index = pkg.requestedPermissions.indexOf(bp.name);
3936        if (index == -1) {
3937            throw new SecurityException("Package " + pkg.packageName
3938                    + " has not requested permission " + bp.name);
3939        }
3940        if (!bp.isRuntime() && !bp.isDevelopment()) {
3941            throw new SecurityException("Permission " + bp.name
3942                    + " is not a changeable permission type");
3943        }
3944    }
3945
3946    @Override
3947    public void grantRuntimePermission(String packageName, String name, final int userId) {
3948        if (!sUserManager.exists(userId)) {
3949            Log.e(TAG, "No such user:" + userId);
3950            return;
3951        }
3952
3953        mContext.enforceCallingOrSelfPermission(
3954                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3955                "grantRuntimePermission");
3956
3957        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3958                true /* requireFullPermission */, true /* checkShell */,
3959                "grantRuntimePermission");
3960
3961        final int uid;
3962        final SettingBase sb;
3963
3964        synchronized (mPackages) {
3965            final PackageParser.Package pkg = mPackages.get(packageName);
3966            if (pkg == null) {
3967                throw new IllegalArgumentException("Unknown package: " + packageName);
3968            }
3969
3970            final BasePermission bp = mSettings.mPermissions.get(name);
3971            if (bp == null) {
3972                throw new IllegalArgumentException("Unknown permission: " + name);
3973            }
3974
3975            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3976
3977            // If a permission review is required for legacy apps we represent
3978            // their permissions as always granted runtime ones since we need
3979            // to keep the review required permission flag per user while an
3980            // install permission's state is shared across all users.
3981            if (Build.PERMISSIONS_REVIEW_REQUIRED
3982                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3983                    && bp.isRuntime()) {
3984                return;
3985            }
3986
3987            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3988            sb = (SettingBase) pkg.mExtras;
3989            if (sb == null) {
3990                throw new IllegalArgumentException("Unknown package: " + packageName);
3991            }
3992
3993            final PermissionsState permissionsState = sb.getPermissionsState();
3994
3995            final int flags = permissionsState.getPermissionFlags(name, userId);
3996            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3997                throw new SecurityException("Cannot grant system fixed permission "
3998                        + name + " for package " + packageName);
3999            }
4000
4001            if (bp.isDevelopment()) {
4002                // Development permissions must be handled specially, since they are not
4003                // normal runtime permissions.  For now they apply to all users.
4004                if (permissionsState.grantInstallPermission(bp) !=
4005                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4006                    scheduleWriteSettingsLocked();
4007                }
4008                return;
4009            }
4010
4011            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4012                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4013                return;
4014            }
4015
4016            final int result = permissionsState.grantRuntimePermission(bp, userId);
4017            switch (result) {
4018                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4019                    return;
4020                }
4021
4022                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4023                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4024                    mHandler.post(new Runnable() {
4025                        @Override
4026                        public void run() {
4027                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4028                        }
4029                    });
4030                }
4031                break;
4032            }
4033
4034            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4035
4036            // Not critical if that is lost - app has to request again.
4037            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4038        }
4039
4040        // Only need to do this if user is initialized. Otherwise it's a new user
4041        // and there are no processes running as the user yet and there's no need
4042        // to make an expensive call to remount processes for the changed permissions.
4043        if (READ_EXTERNAL_STORAGE.equals(name)
4044                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4045            final long token = Binder.clearCallingIdentity();
4046            try {
4047                if (sUserManager.isInitialized(userId)) {
4048                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4049                            MountServiceInternal.class);
4050                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4051                }
4052            } finally {
4053                Binder.restoreCallingIdentity(token);
4054            }
4055        }
4056    }
4057
4058    @Override
4059    public void revokeRuntimePermission(String packageName, String name, int userId) {
4060        if (!sUserManager.exists(userId)) {
4061            Log.e(TAG, "No such user:" + userId);
4062            return;
4063        }
4064
4065        mContext.enforceCallingOrSelfPermission(
4066                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4067                "revokeRuntimePermission");
4068
4069        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4070                true /* requireFullPermission */, true /* checkShell */,
4071                "revokeRuntimePermission");
4072
4073        final int appId;
4074
4075        synchronized (mPackages) {
4076            final PackageParser.Package pkg = mPackages.get(packageName);
4077            if (pkg == null) {
4078                throw new IllegalArgumentException("Unknown package: " + packageName);
4079            }
4080
4081            final BasePermission bp = mSettings.mPermissions.get(name);
4082            if (bp == null) {
4083                throw new IllegalArgumentException("Unknown permission: " + name);
4084            }
4085
4086            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4087
4088            // If a permission review is required for legacy apps we represent
4089            // their permissions as always granted runtime ones since we need
4090            // to keep the review required permission flag per user while an
4091            // install permission's state is shared across all users.
4092            if (Build.PERMISSIONS_REVIEW_REQUIRED
4093                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4094                    && bp.isRuntime()) {
4095                return;
4096            }
4097
4098            SettingBase sb = (SettingBase) pkg.mExtras;
4099            if (sb == null) {
4100                throw new IllegalArgumentException("Unknown package: " + packageName);
4101            }
4102
4103            final PermissionsState permissionsState = sb.getPermissionsState();
4104
4105            final int flags = permissionsState.getPermissionFlags(name, userId);
4106            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4107                throw new SecurityException("Cannot revoke system fixed permission "
4108                        + name + " for package " + packageName);
4109            }
4110
4111            if (bp.isDevelopment()) {
4112                // Development permissions must be handled specially, since they are not
4113                // normal runtime permissions.  For now they apply to all users.
4114                if (permissionsState.revokeInstallPermission(bp) !=
4115                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4116                    scheduleWriteSettingsLocked();
4117                }
4118                return;
4119            }
4120
4121            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4122                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4123                return;
4124            }
4125
4126            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4127
4128            // Critical, after this call app should never have the permission.
4129            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4130
4131            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4132        }
4133
4134        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4135    }
4136
4137    @Override
4138    public void resetRuntimePermissions() {
4139        mContext.enforceCallingOrSelfPermission(
4140                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4141                "revokeRuntimePermission");
4142
4143        int callingUid = Binder.getCallingUid();
4144        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4145            mContext.enforceCallingOrSelfPermission(
4146                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4147                    "resetRuntimePermissions");
4148        }
4149
4150        synchronized (mPackages) {
4151            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4152            for (int userId : UserManagerService.getInstance().getUserIds()) {
4153                final int packageCount = mPackages.size();
4154                for (int i = 0; i < packageCount; i++) {
4155                    PackageParser.Package pkg = mPackages.valueAt(i);
4156                    if (!(pkg.mExtras instanceof PackageSetting)) {
4157                        continue;
4158                    }
4159                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4160                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4161                }
4162            }
4163        }
4164    }
4165
4166    @Override
4167    public int getPermissionFlags(String name, String packageName, int userId) {
4168        if (!sUserManager.exists(userId)) {
4169            return 0;
4170        }
4171
4172        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4173
4174        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4175                true /* requireFullPermission */, false /* checkShell */,
4176                "getPermissionFlags");
4177
4178        synchronized (mPackages) {
4179            final PackageParser.Package pkg = mPackages.get(packageName);
4180            if (pkg == null) {
4181                return 0;
4182            }
4183
4184            final BasePermission bp = mSettings.mPermissions.get(name);
4185            if (bp == null) {
4186                return 0;
4187            }
4188
4189            SettingBase sb = (SettingBase) pkg.mExtras;
4190            if (sb == null) {
4191                return 0;
4192            }
4193
4194            PermissionsState permissionsState = sb.getPermissionsState();
4195            return permissionsState.getPermissionFlags(name, userId);
4196        }
4197    }
4198
4199    @Override
4200    public void updatePermissionFlags(String name, String packageName, int flagMask,
4201            int flagValues, int userId) {
4202        if (!sUserManager.exists(userId)) {
4203            return;
4204        }
4205
4206        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4207
4208        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4209                true /* requireFullPermission */, true /* checkShell */,
4210                "updatePermissionFlags");
4211
4212        // Only the system can change these flags and nothing else.
4213        if (getCallingUid() != Process.SYSTEM_UID) {
4214            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4215            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4216            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4217            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4218            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4219        }
4220
4221        synchronized (mPackages) {
4222            final PackageParser.Package pkg = mPackages.get(packageName);
4223            if (pkg == null) {
4224                throw new IllegalArgumentException("Unknown package: " + packageName);
4225            }
4226
4227            final BasePermission bp = mSettings.mPermissions.get(name);
4228            if (bp == null) {
4229                throw new IllegalArgumentException("Unknown permission: " + name);
4230            }
4231
4232            SettingBase sb = (SettingBase) pkg.mExtras;
4233            if (sb == null) {
4234                throw new IllegalArgumentException("Unknown package: " + packageName);
4235            }
4236
4237            PermissionsState permissionsState = sb.getPermissionsState();
4238
4239            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4240
4241            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4242                // Install and runtime permissions are stored in different places,
4243                // so figure out what permission changed and persist the change.
4244                if (permissionsState.getInstallPermissionState(name) != null) {
4245                    scheduleWriteSettingsLocked();
4246                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4247                        || hadState) {
4248                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4249                }
4250            }
4251        }
4252    }
4253
4254    /**
4255     * Update the permission flags for all packages and runtime permissions of a user in order
4256     * to allow device or profile owner to remove POLICY_FIXED.
4257     */
4258    @Override
4259    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4260        if (!sUserManager.exists(userId)) {
4261            return;
4262        }
4263
4264        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4265
4266        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4267                true /* requireFullPermission */, true /* checkShell */,
4268                "updatePermissionFlagsForAllApps");
4269
4270        // Only the system can change system fixed flags.
4271        if (getCallingUid() != Process.SYSTEM_UID) {
4272            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4273            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4274        }
4275
4276        synchronized (mPackages) {
4277            boolean changed = false;
4278            final int packageCount = mPackages.size();
4279            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4280                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4281                SettingBase sb = (SettingBase) pkg.mExtras;
4282                if (sb == null) {
4283                    continue;
4284                }
4285                PermissionsState permissionsState = sb.getPermissionsState();
4286                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4287                        userId, flagMask, flagValues);
4288            }
4289            if (changed) {
4290                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4291            }
4292        }
4293    }
4294
4295    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4296        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4297                != PackageManager.PERMISSION_GRANTED
4298            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4299                != PackageManager.PERMISSION_GRANTED) {
4300            throw new SecurityException(message + " requires "
4301                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4302                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4303        }
4304    }
4305
4306    @Override
4307    public boolean shouldShowRequestPermissionRationale(String permissionName,
4308            String packageName, int userId) {
4309        if (UserHandle.getCallingUserId() != userId) {
4310            mContext.enforceCallingPermission(
4311                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4312                    "canShowRequestPermissionRationale for user " + userId);
4313        }
4314
4315        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4316        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4317            return false;
4318        }
4319
4320        if (checkPermission(permissionName, packageName, userId)
4321                == PackageManager.PERMISSION_GRANTED) {
4322            return false;
4323        }
4324
4325        final int flags;
4326
4327        final long identity = Binder.clearCallingIdentity();
4328        try {
4329            flags = getPermissionFlags(permissionName,
4330                    packageName, userId);
4331        } finally {
4332            Binder.restoreCallingIdentity(identity);
4333        }
4334
4335        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4336                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4337                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4338
4339        if ((flags & fixedFlags) != 0) {
4340            return false;
4341        }
4342
4343        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4344    }
4345
4346    @Override
4347    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4348        mContext.enforceCallingOrSelfPermission(
4349                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4350                "addOnPermissionsChangeListener");
4351
4352        synchronized (mPackages) {
4353            mOnPermissionChangeListeners.addListenerLocked(listener);
4354        }
4355    }
4356
4357    @Override
4358    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4359        synchronized (mPackages) {
4360            mOnPermissionChangeListeners.removeListenerLocked(listener);
4361        }
4362    }
4363
4364    @Override
4365    public boolean isProtectedBroadcast(String actionName) {
4366        synchronized (mPackages) {
4367            if (mProtectedBroadcasts.contains(actionName)) {
4368                return true;
4369            } else if (actionName != null) {
4370                // TODO: remove these terrible hacks
4371                if (actionName.startsWith("android.net.netmon.lingerExpired")
4372                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4373                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4374                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4375                    return true;
4376                }
4377            }
4378        }
4379        return false;
4380    }
4381
4382    @Override
4383    public int checkSignatures(String pkg1, String pkg2) {
4384        synchronized (mPackages) {
4385            final PackageParser.Package p1 = mPackages.get(pkg1);
4386            final PackageParser.Package p2 = mPackages.get(pkg2);
4387            if (p1 == null || p1.mExtras == null
4388                    || p2 == null || p2.mExtras == null) {
4389                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4390            }
4391            return compareSignatures(p1.mSignatures, p2.mSignatures);
4392        }
4393    }
4394
4395    @Override
4396    public int checkUidSignatures(int uid1, int uid2) {
4397        // Map to base uids.
4398        uid1 = UserHandle.getAppId(uid1);
4399        uid2 = UserHandle.getAppId(uid2);
4400        // reader
4401        synchronized (mPackages) {
4402            Signature[] s1;
4403            Signature[] s2;
4404            Object obj = mSettings.getUserIdLPr(uid1);
4405            if (obj != null) {
4406                if (obj instanceof SharedUserSetting) {
4407                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4408                } else if (obj instanceof PackageSetting) {
4409                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4410                } else {
4411                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4412                }
4413            } else {
4414                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4415            }
4416            obj = mSettings.getUserIdLPr(uid2);
4417            if (obj != null) {
4418                if (obj instanceof SharedUserSetting) {
4419                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4420                } else if (obj instanceof PackageSetting) {
4421                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4422                } else {
4423                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4424                }
4425            } else {
4426                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4427            }
4428            return compareSignatures(s1, s2);
4429        }
4430    }
4431
4432    /**
4433     * This method should typically only be used when granting or revoking
4434     * permissions, since the app may immediately restart after this call.
4435     * <p>
4436     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4437     * guard your work against the app being relaunched.
4438     */
4439    private void killUid(int appId, int userId, String reason) {
4440        final long identity = Binder.clearCallingIdentity();
4441        try {
4442            IActivityManager am = ActivityManagerNative.getDefault();
4443            if (am != null) {
4444                try {
4445                    am.killUid(appId, userId, reason);
4446                } catch (RemoteException e) {
4447                    /* ignore - same process */
4448                }
4449            }
4450        } finally {
4451            Binder.restoreCallingIdentity(identity);
4452        }
4453    }
4454
4455    /**
4456     * Compares two sets of signatures. Returns:
4457     * <br />
4458     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4459     * <br />
4460     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4461     * <br />
4462     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4463     * <br />
4464     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4465     * <br />
4466     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4467     */
4468    static int compareSignatures(Signature[] s1, Signature[] s2) {
4469        if (s1 == null) {
4470            return s2 == null
4471                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4472                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4473        }
4474
4475        if (s2 == null) {
4476            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4477        }
4478
4479        if (s1.length != s2.length) {
4480            return PackageManager.SIGNATURE_NO_MATCH;
4481        }
4482
4483        // Since both signature sets are of size 1, we can compare without HashSets.
4484        if (s1.length == 1) {
4485            return s1[0].equals(s2[0]) ?
4486                    PackageManager.SIGNATURE_MATCH :
4487                    PackageManager.SIGNATURE_NO_MATCH;
4488        }
4489
4490        ArraySet<Signature> set1 = new ArraySet<Signature>();
4491        for (Signature sig : s1) {
4492            set1.add(sig);
4493        }
4494        ArraySet<Signature> set2 = new ArraySet<Signature>();
4495        for (Signature sig : s2) {
4496            set2.add(sig);
4497        }
4498        // Make sure s2 contains all signatures in s1.
4499        if (set1.equals(set2)) {
4500            return PackageManager.SIGNATURE_MATCH;
4501        }
4502        return PackageManager.SIGNATURE_NO_MATCH;
4503    }
4504
4505    /**
4506     * If the database version for this type of package (internal storage or
4507     * external storage) is less than the version where package signatures
4508     * were updated, return true.
4509     */
4510    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4511        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4512        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4513    }
4514
4515    /**
4516     * Used for backward compatibility to make sure any packages with
4517     * certificate chains get upgraded to the new style. {@code existingSigs}
4518     * will be in the old format (since they were stored on disk from before the
4519     * system upgrade) and {@code scannedSigs} will be in the newer format.
4520     */
4521    private int compareSignaturesCompat(PackageSignatures existingSigs,
4522            PackageParser.Package scannedPkg) {
4523        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4524            return PackageManager.SIGNATURE_NO_MATCH;
4525        }
4526
4527        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4528        for (Signature sig : existingSigs.mSignatures) {
4529            existingSet.add(sig);
4530        }
4531        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4532        for (Signature sig : scannedPkg.mSignatures) {
4533            try {
4534                Signature[] chainSignatures = sig.getChainSignatures();
4535                for (Signature chainSig : chainSignatures) {
4536                    scannedCompatSet.add(chainSig);
4537                }
4538            } catch (CertificateEncodingException e) {
4539                scannedCompatSet.add(sig);
4540            }
4541        }
4542        /*
4543         * Make sure the expanded scanned set contains all signatures in the
4544         * existing one.
4545         */
4546        if (scannedCompatSet.equals(existingSet)) {
4547            // Migrate the old signatures to the new scheme.
4548            existingSigs.assignSignatures(scannedPkg.mSignatures);
4549            // The new KeySets will be re-added later in the scanning process.
4550            synchronized (mPackages) {
4551                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4552            }
4553            return PackageManager.SIGNATURE_MATCH;
4554        }
4555        return PackageManager.SIGNATURE_NO_MATCH;
4556    }
4557
4558    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4559        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4560        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4561    }
4562
4563    private int compareSignaturesRecover(PackageSignatures existingSigs,
4564            PackageParser.Package scannedPkg) {
4565        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4566            return PackageManager.SIGNATURE_NO_MATCH;
4567        }
4568
4569        String msg = null;
4570        try {
4571            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4572                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4573                        + scannedPkg.packageName);
4574                return PackageManager.SIGNATURE_MATCH;
4575            }
4576        } catch (CertificateException e) {
4577            msg = e.getMessage();
4578        }
4579
4580        logCriticalInfo(Log.INFO,
4581                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4582        return PackageManager.SIGNATURE_NO_MATCH;
4583    }
4584
4585    @Override
4586    public List<String> getAllPackages() {
4587        synchronized (mPackages) {
4588            return new ArrayList<String>(mPackages.keySet());
4589        }
4590    }
4591
4592    @Override
4593    public String[] getPackagesForUid(int uid) {
4594        uid = UserHandle.getAppId(uid);
4595        // reader
4596        synchronized (mPackages) {
4597            Object obj = mSettings.getUserIdLPr(uid);
4598            if (obj instanceof SharedUserSetting) {
4599                final SharedUserSetting sus = (SharedUserSetting) obj;
4600                final int N = sus.packages.size();
4601                final String[] res = new String[N];
4602                for (int i = 0; i < N; i++) {
4603                    res[i] = sus.packages.valueAt(i).name;
4604                }
4605                return res;
4606            } else if (obj instanceof PackageSetting) {
4607                final PackageSetting ps = (PackageSetting) obj;
4608                return new String[] { ps.name };
4609            }
4610        }
4611        return null;
4612    }
4613
4614    @Override
4615    public String getNameForUid(int uid) {
4616        // reader
4617        synchronized (mPackages) {
4618            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4619            if (obj instanceof SharedUserSetting) {
4620                final SharedUserSetting sus = (SharedUserSetting) obj;
4621                return sus.name + ":" + sus.userId;
4622            } else if (obj instanceof PackageSetting) {
4623                final PackageSetting ps = (PackageSetting) obj;
4624                return ps.name;
4625            }
4626        }
4627        return null;
4628    }
4629
4630    @Override
4631    public int getUidForSharedUser(String sharedUserName) {
4632        if(sharedUserName == null) {
4633            return -1;
4634        }
4635        // reader
4636        synchronized (mPackages) {
4637            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4638            if (suid == null) {
4639                return -1;
4640            }
4641            return suid.userId;
4642        }
4643    }
4644
4645    @Override
4646    public int getFlagsForUid(int uid) {
4647        synchronized (mPackages) {
4648            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4649            if (obj instanceof SharedUserSetting) {
4650                final SharedUserSetting sus = (SharedUserSetting) obj;
4651                return sus.pkgFlags;
4652            } else if (obj instanceof PackageSetting) {
4653                final PackageSetting ps = (PackageSetting) obj;
4654                return ps.pkgFlags;
4655            }
4656        }
4657        return 0;
4658    }
4659
4660    @Override
4661    public int getPrivateFlagsForUid(int uid) {
4662        synchronized (mPackages) {
4663            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4664            if (obj instanceof SharedUserSetting) {
4665                final SharedUserSetting sus = (SharedUserSetting) obj;
4666                return sus.pkgPrivateFlags;
4667            } else if (obj instanceof PackageSetting) {
4668                final PackageSetting ps = (PackageSetting) obj;
4669                return ps.pkgPrivateFlags;
4670            }
4671        }
4672        return 0;
4673    }
4674
4675    @Override
4676    public boolean isUidPrivileged(int uid) {
4677        uid = UserHandle.getAppId(uid);
4678        // reader
4679        synchronized (mPackages) {
4680            Object obj = mSettings.getUserIdLPr(uid);
4681            if (obj instanceof SharedUserSetting) {
4682                final SharedUserSetting sus = (SharedUserSetting) obj;
4683                final Iterator<PackageSetting> it = sus.packages.iterator();
4684                while (it.hasNext()) {
4685                    if (it.next().isPrivileged()) {
4686                        return true;
4687                    }
4688                }
4689            } else if (obj instanceof PackageSetting) {
4690                final PackageSetting ps = (PackageSetting) obj;
4691                return ps.isPrivileged();
4692            }
4693        }
4694        return false;
4695    }
4696
4697    @Override
4698    public String[] getAppOpPermissionPackages(String permissionName) {
4699        synchronized (mPackages) {
4700            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4701            if (pkgs == null) {
4702                return null;
4703            }
4704            return pkgs.toArray(new String[pkgs.size()]);
4705        }
4706    }
4707
4708    @Override
4709    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4710            int flags, int userId) {
4711        try {
4712            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4713
4714            if (!sUserManager.exists(userId)) return null;
4715            flags = updateFlagsForResolve(flags, userId, intent);
4716            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4717                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4718
4719            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4720            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4721                    flags, userId);
4722            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4723
4724            final ResolveInfo bestChoice =
4725                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4726
4727            if (isEphemeralAllowed(intent, query, userId)) {
4728                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4729                final EphemeralResolveInfo ai =
4730                        getEphemeralResolveInfo(intent, resolvedType, userId);
4731                if (ai != null) {
4732                    if (DEBUG_EPHEMERAL) {
4733                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4734                    }
4735                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4736                    bestChoice.ephemeralResolveInfo = ai;
4737                }
4738                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4739            }
4740            return bestChoice;
4741        } finally {
4742            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4743        }
4744    }
4745
4746    @Override
4747    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4748            IntentFilter filter, int match, ComponentName activity) {
4749        final int userId = UserHandle.getCallingUserId();
4750        if (DEBUG_PREFERRED) {
4751            Log.v(TAG, "setLastChosenActivity intent=" + intent
4752                + " resolvedType=" + resolvedType
4753                + " flags=" + flags
4754                + " filter=" + filter
4755                + " match=" + match
4756                + " activity=" + activity);
4757            filter.dump(new PrintStreamPrinter(System.out), "    ");
4758        }
4759        intent.setComponent(null);
4760        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4761                userId);
4762        // Find any earlier preferred or last chosen entries and nuke them
4763        findPreferredActivity(intent, resolvedType,
4764                flags, query, 0, false, true, false, userId);
4765        // Add the new activity as the last chosen for this filter
4766        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4767                "Setting last chosen");
4768    }
4769
4770    @Override
4771    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4772        final int userId = UserHandle.getCallingUserId();
4773        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4774        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4775                userId);
4776        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4777                false, false, false, userId);
4778    }
4779
4780
4781    private boolean isEphemeralAllowed(
4782            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4783        // Short circuit and return early if possible.
4784        if (DISABLE_EPHEMERAL_APPS) {
4785            return false;
4786        }
4787        final int callingUser = UserHandle.getCallingUserId();
4788        if (callingUser != UserHandle.USER_SYSTEM) {
4789            return false;
4790        }
4791        if (mEphemeralResolverConnection == null) {
4792            return false;
4793        }
4794        if (intent.getComponent() != null) {
4795            return false;
4796        }
4797        if (intent.getPackage() != null) {
4798            return false;
4799        }
4800        final boolean isWebUri = hasWebURI(intent);
4801        if (!isWebUri) {
4802            return false;
4803        }
4804        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4805        synchronized (mPackages) {
4806            final int count = resolvedActivites.size();
4807            for (int n = 0; n < count; n++) {
4808                ResolveInfo info = resolvedActivites.get(n);
4809                String packageName = info.activityInfo.packageName;
4810                PackageSetting ps = mSettings.mPackages.get(packageName);
4811                if (ps != null) {
4812                    // Try to get the status from User settings first
4813                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4814                    int status = (int) (packedStatus >> 32);
4815                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4816                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4817                        if (DEBUG_EPHEMERAL) {
4818                            Slog.v(TAG, "DENY ephemeral apps;"
4819                                + " pkg: " + packageName + ", status: " + status);
4820                        }
4821                        return false;
4822                    }
4823                }
4824            }
4825        }
4826        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4827        return true;
4828    }
4829
4830    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4831            int userId) {
4832        final int ephemeralPrefixMask = Global.getInt(mContext.getContentResolver(),
4833                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4834        final int ephemeralPrefixCount = Global.getInt(mContext.getContentResolver(),
4835                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4836        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4837                ephemeralPrefixCount);
4838        final int[] shaPrefix = digest.getDigestPrefix();
4839        final byte[][] digestBytes = digest.getDigestBytes();
4840        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4841                mEphemeralResolverConnection.getEphemeralResolveInfoList(
4842                        shaPrefix, ephemeralPrefixMask);
4843        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4844            // No hash prefix match; there are no ephemeral apps for this domain.
4845            return null;
4846        }
4847
4848        // Go in reverse order so we match the narrowest scope first.
4849        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4850            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4851                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4852                    continue;
4853                }
4854                final List<IntentFilter> filters = ephemeralApplication.getFilters();
4855                // No filters; this should never happen.
4856                if (filters.isEmpty()) {
4857                    continue;
4858                }
4859                // We have a domain match; resolve the filters to see if anything matches.
4860                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4861                for (int j = filters.size() - 1; j >= 0; --j) {
4862                    final EphemeralResolveIntentInfo intentInfo =
4863                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4864                    ephemeralResolver.addFilter(intentInfo);
4865                }
4866                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4867                        intent, resolvedType, false /*defaultOnly*/, userId);
4868                if (!matchedResolveInfoList.isEmpty()) {
4869                    return matchedResolveInfoList.get(0);
4870                }
4871            }
4872        }
4873        // Hash or filter mis-match; no ephemeral apps for this domain.
4874        return null;
4875    }
4876
4877    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4878            int flags, List<ResolveInfo> query, int userId) {
4879        if (query != null) {
4880            final int N = query.size();
4881            if (N == 1) {
4882                return query.get(0);
4883            } else if (N > 1) {
4884                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4885                // If there is more than one activity with the same priority,
4886                // then let the user decide between them.
4887                ResolveInfo r0 = query.get(0);
4888                ResolveInfo r1 = query.get(1);
4889                if (DEBUG_INTENT_MATCHING || debug) {
4890                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4891                            + r1.activityInfo.name + "=" + r1.priority);
4892                }
4893                // If the first activity has a higher priority, or a different
4894                // default, then it is always desirable to pick it.
4895                if (r0.priority != r1.priority
4896                        || r0.preferredOrder != r1.preferredOrder
4897                        || r0.isDefault != r1.isDefault) {
4898                    return query.get(0);
4899                }
4900                // If we have saved a preference for a preferred activity for
4901                // this Intent, use that.
4902                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4903                        flags, query, r0.priority, true, false, debug, userId);
4904                if (ri != null) {
4905                    return ri;
4906                }
4907                ri = new ResolveInfo(mResolveInfo);
4908                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4909                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
4910                // If all of the options come from the same package, show the application's
4911                // label and icon instead of the generic resolver's.
4912                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
4913                // and then throw away the ResolveInfo itself, meaning that the caller loses
4914                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
4915                // a fallback for this case; we only set the target package's resources on
4916                // the ResolveInfo, not the ActivityInfo.
4917                final String intentPackage = intent.getPackage();
4918                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
4919                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
4920                    ri.resolvePackageName = intentPackage;
4921                    if (userNeedsBadging(userId)) {
4922                        ri.noResourceId = true;
4923                    } else {
4924                        ri.icon = appi.icon;
4925                    }
4926                    ri.iconResourceId = appi.icon;
4927                    ri.labelRes = appi.labelRes;
4928                }
4929                ri.activityInfo.applicationInfo = new ApplicationInfo(
4930                        ri.activityInfo.applicationInfo);
4931                if (userId != 0) {
4932                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4933                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4934                }
4935                // Make sure that the resolver is displayable in car mode
4936                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4937                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4938                return ri;
4939            }
4940        }
4941        return null;
4942    }
4943
4944    /**
4945     * Return true if the given list is not empty and all of its contents have
4946     * an activityInfo with the given package name.
4947     */
4948    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
4949        if (ArrayUtils.isEmpty(list)) {
4950            return false;
4951        }
4952        for (int i = 0, N = list.size(); i < N; i++) {
4953            final ResolveInfo ri = list.get(i);
4954            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
4955            if (ai == null || !packageName.equals(ai.packageName)) {
4956                return false;
4957            }
4958        }
4959        return true;
4960    }
4961
4962    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4963            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4964        final int N = query.size();
4965        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4966                .get(userId);
4967        // Get the list of persistent preferred activities that handle the intent
4968        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4969        List<PersistentPreferredActivity> pprefs = ppir != null
4970                ? ppir.queryIntent(intent, resolvedType,
4971                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4972                : null;
4973        if (pprefs != null && pprefs.size() > 0) {
4974            final int M = pprefs.size();
4975            for (int i=0; i<M; i++) {
4976                final PersistentPreferredActivity ppa = pprefs.get(i);
4977                if (DEBUG_PREFERRED || debug) {
4978                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4979                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4980                            + "\n  component=" + ppa.mComponent);
4981                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4982                }
4983                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4984                        flags | MATCH_DISABLED_COMPONENTS, userId);
4985                if (DEBUG_PREFERRED || debug) {
4986                    Slog.v(TAG, "Found persistent preferred activity:");
4987                    if (ai != null) {
4988                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4989                    } else {
4990                        Slog.v(TAG, "  null");
4991                    }
4992                }
4993                if (ai == null) {
4994                    // This previously registered persistent preferred activity
4995                    // component is no longer known. Ignore it and do NOT remove it.
4996                    continue;
4997                }
4998                for (int j=0; j<N; j++) {
4999                    final ResolveInfo ri = query.get(j);
5000                    if (!ri.activityInfo.applicationInfo.packageName
5001                            .equals(ai.applicationInfo.packageName)) {
5002                        continue;
5003                    }
5004                    if (!ri.activityInfo.name.equals(ai.name)) {
5005                        continue;
5006                    }
5007                    //  Found a persistent preference that can handle the intent.
5008                    if (DEBUG_PREFERRED || debug) {
5009                        Slog.v(TAG, "Returning persistent preferred activity: " +
5010                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5011                    }
5012                    return ri;
5013                }
5014            }
5015        }
5016        return null;
5017    }
5018
5019    // TODO: handle preferred activities missing while user has amnesia
5020    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5021            List<ResolveInfo> query, int priority, boolean always,
5022            boolean removeMatches, boolean debug, int userId) {
5023        if (!sUserManager.exists(userId)) return null;
5024        flags = updateFlagsForResolve(flags, userId, intent);
5025        // writer
5026        synchronized (mPackages) {
5027            if (intent.getSelector() != null) {
5028                intent = intent.getSelector();
5029            }
5030            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5031
5032            // Try to find a matching persistent preferred activity.
5033            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5034                    debug, userId);
5035
5036            // If a persistent preferred activity matched, use it.
5037            if (pri != null) {
5038                return pri;
5039            }
5040
5041            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5042            // Get the list of preferred activities that handle the intent
5043            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5044            List<PreferredActivity> prefs = pir != null
5045                    ? pir.queryIntent(intent, resolvedType,
5046                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5047                    : null;
5048            if (prefs != null && prefs.size() > 0) {
5049                boolean changed = false;
5050                try {
5051                    // First figure out how good the original match set is.
5052                    // We will only allow preferred activities that came
5053                    // from the same match quality.
5054                    int match = 0;
5055
5056                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5057
5058                    final int N = query.size();
5059                    for (int j=0; j<N; j++) {
5060                        final ResolveInfo ri = query.get(j);
5061                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5062                                + ": 0x" + Integer.toHexString(match));
5063                        if (ri.match > match) {
5064                            match = ri.match;
5065                        }
5066                    }
5067
5068                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5069                            + Integer.toHexString(match));
5070
5071                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5072                    final int M = prefs.size();
5073                    for (int i=0; i<M; i++) {
5074                        final PreferredActivity pa = prefs.get(i);
5075                        if (DEBUG_PREFERRED || debug) {
5076                            Slog.v(TAG, "Checking PreferredActivity ds="
5077                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5078                                    + "\n  component=" + pa.mPref.mComponent);
5079                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5080                        }
5081                        if (pa.mPref.mMatch != match) {
5082                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5083                                    + Integer.toHexString(pa.mPref.mMatch));
5084                            continue;
5085                        }
5086                        // If it's not an "always" type preferred activity and that's what we're
5087                        // looking for, skip it.
5088                        if (always && !pa.mPref.mAlways) {
5089                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5090                            continue;
5091                        }
5092                        final ActivityInfo ai = getActivityInfo(
5093                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5094                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5095                                userId);
5096                        if (DEBUG_PREFERRED || debug) {
5097                            Slog.v(TAG, "Found preferred activity:");
5098                            if (ai != null) {
5099                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5100                            } else {
5101                                Slog.v(TAG, "  null");
5102                            }
5103                        }
5104                        if (ai == null) {
5105                            // This previously registered preferred activity
5106                            // component is no longer known.  Most likely an update
5107                            // to the app was installed and in the new version this
5108                            // component no longer exists.  Clean it up by removing
5109                            // it from the preferred activities list, and skip it.
5110                            Slog.w(TAG, "Removing dangling preferred activity: "
5111                                    + pa.mPref.mComponent);
5112                            pir.removeFilter(pa);
5113                            changed = true;
5114                            continue;
5115                        }
5116                        for (int j=0; j<N; j++) {
5117                            final ResolveInfo ri = query.get(j);
5118                            if (!ri.activityInfo.applicationInfo.packageName
5119                                    .equals(ai.applicationInfo.packageName)) {
5120                                continue;
5121                            }
5122                            if (!ri.activityInfo.name.equals(ai.name)) {
5123                                continue;
5124                            }
5125
5126                            if (removeMatches) {
5127                                pir.removeFilter(pa);
5128                                changed = true;
5129                                if (DEBUG_PREFERRED) {
5130                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5131                                }
5132                                break;
5133                            }
5134
5135                            // Okay we found a previously set preferred or last chosen app.
5136                            // If the result set is different from when this
5137                            // was created, we need to clear it and re-ask the
5138                            // user their preference, if we're looking for an "always" type entry.
5139                            if (always && !pa.mPref.sameSet(query)) {
5140                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5141                                        + intent + " type " + resolvedType);
5142                                if (DEBUG_PREFERRED) {
5143                                    Slog.v(TAG, "Removing preferred activity since set changed "
5144                                            + pa.mPref.mComponent);
5145                                }
5146                                pir.removeFilter(pa);
5147                                // Re-add the filter as a "last chosen" entry (!always)
5148                                PreferredActivity lastChosen = new PreferredActivity(
5149                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5150                                pir.addFilter(lastChosen);
5151                                changed = true;
5152                                return null;
5153                            }
5154
5155                            // Yay! Either the set matched or we're looking for the last chosen
5156                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5157                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5158                            return ri;
5159                        }
5160                    }
5161                } finally {
5162                    if (changed) {
5163                        if (DEBUG_PREFERRED) {
5164                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5165                        }
5166                        scheduleWritePackageRestrictionsLocked(userId);
5167                    }
5168                }
5169            }
5170        }
5171        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5172        return null;
5173    }
5174
5175    /*
5176     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5177     */
5178    @Override
5179    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5180            int targetUserId) {
5181        mContext.enforceCallingOrSelfPermission(
5182                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5183        List<CrossProfileIntentFilter> matches =
5184                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5185        if (matches != null) {
5186            int size = matches.size();
5187            for (int i = 0; i < size; i++) {
5188                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5189            }
5190        }
5191        if (hasWebURI(intent)) {
5192            // cross-profile app linking works only towards the parent.
5193            final UserInfo parent = getProfileParent(sourceUserId);
5194            synchronized(mPackages) {
5195                int flags = updateFlagsForResolve(0, parent.id, intent);
5196                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5197                        intent, resolvedType, flags, sourceUserId, parent.id);
5198                return xpDomainInfo != null;
5199            }
5200        }
5201        return false;
5202    }
5203
5204    private UserInfo getProfileParent(int userId) {
5205        final long identity = Binder.clearCallingIdentity();
5206        try {
5207            return sUserManager.getProfileParent(userId);
5208        } finally {
5209            Binder.restoreCallingIdentity(identity);
5210        }
5211    }
5212
5213    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5214            String resolvedType, int userId) {
5215        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5216        if (resolver != null) {
5217            return resolver.queryIntent(intent, resolvedType, false, userId);
5218        }
5219        return null;
5220    }
5221
5222    @Override
5223    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5224            String resolvedType, int flags, int userId) {
5225        try {
5226            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5227
5228            return new ParceledListSlice<>(
5229                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5230        } finally {
5231            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5232        }
5233    }
5234
5235    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5236            String resolvedType, int flags, int userId) {
5237        if (!sUserManager.exists(userId)) return Collections.emptyList();
5238        flags = updateFlagsForResolve(flags, userId, intent);
5239        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5240                false /* requireFullPermission */, false /* checkShell */,
5241                "query intent activities");
5242        ComponentName comp = intent.getComponent();
5243        if (comp == null) {
5244            if (intent.getSelector() != null) {
5245                intent = intent.getSelector();
5246                comp = intent.getComponent();
5247            }
5248        }
5249
5250        if (comp != null) {
5251            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5252            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5253            if (ai != null) {
5254                final ResolveInfo ri = new ResolveInfo();
5255                ri.activityInfo = ai;
5256                list.add(ri);
5257            }
5258            return list;
5259        }
5260
5261        // reader
5262        synchronized (mPackages) {
5263            final String pkgName = intent.getPackage();
5264            if (pkgName == null) {
5265                List<CrossProfileIntentFilter> matchingFilters =
5266                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5267                // Check for results that need to skip the current profile.
5268                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5269                        resolvedType, flags, userId);
5270                if (xpResolveInfo != null) {
5271                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5272                    result.add(xpResolveInfo);
5273                    return filterIfNotSystemUser(result, userId);
5274                }
5275
5276                // Check for results in the current profile.
5277                List<ResolveInfo> result = mActivities.queryIntent(
5278                        intent, resolvedType, flags, userId);
5279                result = filterIfNotSystemUser(result, userId);
5280
5281                // Check for cross profile results.
5282                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5283                xpResolveInfo = queryCrossProfileIntents(
5284                        matchingFilters, intent, resolvedType, flags, userId,
5285                        hasNonNegativePriorityResult);
5286                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5287                    boolean isVisibleToUser = filterIfNotSystemUser(
5288                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5289                    if (isVisibleToUser) {
5290                        result.add(xpResolveInfo);
5291                        Collections.sort(result, mResolvePrioritySorter);
5292                    }
5293                }
5294                if (hasWebURI(intent)) {
5295                    CrossProfileDomainInfo xpDomainInfo = null;
5296                    final UserInfo parent = getProfileParent(userId);
5297                    if (parent != null) {
5298                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5299                                flags, userId, parent.id);
5300                    }
5301                    if (xpDomainInfo != null) {
5302                        if (xpResolveInfo != null) {
5303                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5304                            // in the result.
5305                            result.remove(xpResolveInfo);
5306                        }
5307                        if (result.size() == 0) {
5308                            result.add(xpDomainInfo.resolveInfo);
5309                            return result;
5310                        }
5311                    } else if (result.size() <= 1) {
5312                        return result;
5313                    }
5314                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5315                            xpDomainInfo, userId);
5316                    Collections.sort(result, mResolvePrioritySorter);
5317                }
5318                return result;
5319            }
5320            final PackageParser.Package pkg = mPackages.get(pkgName);
5321            if (pkg != null) {
5322                return filterIfNotSystemUser(
5323                        mActivities.queryIntentForPackage(
5324                                intent, resolvedType, flags, pkg.activities, userId),
5325                        userId);
5326            }
5327            return new ArrayList<ResolveInfo>();
5328        }
5329    }
5330
5331    private static class CrossProfileDomainInfo {
5332        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5333        ResolveInfo resolveInfo;
5334        /* Best domain verification status of the activities found in the other profile */
5335        int bestDomainVerificationStatus;
5336    }
5337
5338    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5339            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5340        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5341                sourceUserId)) {
5342            return null;
5343        }
5344        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5345                resolvedType, flags, parentUserId);
5346
5347        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5348            return null;
5349        }
5350        CrossProfileDomainInfo result = null;
5351        int size = resultTargetUser.size();
5352        for (int i = 0; i < size; i++) {
5353            ResolveInfo riTargetUser = resultTargetUser.get(i);
5354            // Intent filter verification is only for filters that specify a host. So don't return
5355            // those that handle all web uris.
5356            if (riTargetUser.handleAllWebDataURI) {
5357                continue;
5358            }
5359            String packageName = riTargetUser.activityInfo.packageName;
5360            PackageSetting ps = mSettings.mPackages.get(packageName);
5361            if (ps == null) {
5362                continue;
5363            }
5364            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5365            int status = (int)(verificationState >> 32);
5366            if (result == null) {
5367                result = new CrossProfileDomainInfo();
5368                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5369                        sourceUserId, parentUserId);
5370                result.bestDomainVerificationStatus = status;
5371            } else {
5372                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5373                        result.bestDomainVerificationStatus);
5374            }
5375        }
5376        // Don't consider matches with status NEVER across profiles.
5377        if (result != null && result.bestDomainVerificationStatus
5378                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5379            return null;
5380        }
5381        return result;
5382    }
5383
5384    /**
5385     * Verification statuses are ordered from the worse to the best, except for
5386     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5387     */
5388    private int bestDomainVerificationStatus(int status1, int status2) {
5389        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5390            return status2;
5391        }
5392        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5393            return status1;
5394        }
5395        return (int) MathUtils.max(status1, status2);
5396    }
5397
5398    private boolean isUserEnabled(int userId) {
5399        long callingId = Binder.clearCallingIdentity();
5400        try {
5401            UserInfo userInfo = sUserManager.getUserInfo(userId);
5402            return userInfo != null && userInfo.isEnabled();
5403        } finally {
5404            Binder.restoreCallingIdentity(callingId);
5405        }
5406    }
5407
5408    /**
5409     * Filter out activities with systemUserOnly flag set, when current user is not System.
5410     *
5411     * @return filtered list
5412     */
5413    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5414        if (userId == UserHandle.USER_SYSTEM) {
5415            return resolveInfos;
5416        }
5417        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5418            ResolveInfo info = resolveInfos.get(i);
5419            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5420                resolveInfos.remove(i);
5421            }
5422        }
5423        return resolveInfos;
5424    }
5425
5426    /**
5427     * @param resolveInfos list of resolve infos in descending priority order
5428     * @return if the list contains a resolve info with non-negative priority
5429     */
5430    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5431        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5432    }
5433
5434    private static boolean hasWebURI(Intent intent) {
5435        if (intent.getData() == null) {
5436            return false;
5437        }
5438        final String scheme = intent.getScheme();
5439        if (TextUtils.isEmpty(scheme)) {
5440            return false;
5441        }
5442        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5443    }
5444
5445    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5446            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5447            int userId) {
5448        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5449
5450        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5451            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5452                    candidates.size());
5453        }
5454
5455        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5456        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5457        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5458        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5459        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5460        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5461
5462        synchronized (mPackages) {
5463            final int count = candidates.size();
5464            // First, try to use linked apps. Partition the candidates into four lists:
5465            // one for the final results, one for the "do not use ever", one for "undefined status"
5466            // and finally one for "browser app type".
5467            for (int n=0; n<count; n++) {
5468                ResolveInfo info = candidates.get(n);
5469                String packageName = info.activityInfo.packageName;
5470                PackageSetting ps = mSettings.mPackages.get(packageName);
5471                if (ps != null) {
5472                    // Add to the special match all list (Browser use case)
5473                    if (info.handleAllWebDataURI) {
5474                        matchAllList.add(info);
5475                        continue;
5476                    }
5477                    // Try to get the status from User settings first
5478                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5479                    int status = (int)(packedStatus >> 32);
5480                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5481                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5482                        if (DEBUG_DOMAIN_VERIFICATION) {
5483                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5484                                    + " : linkgen=" + linkGeneration);
5485                        }
5486                        // Use link-enabled generation as preferredOrder, i.e.
5487                        // prefer newly-enabled over earlier-enabled.
5488                        info.preferredOrder = linkGeneration;
5489                        alwaysList.add(info);
5490                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5491                        if (DEBUG_DOMAIN_VERIFICATION) {
5492                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5493                        }
5494                        neverList.add(info);
5495                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5496                        if (DEBUG_DOMAIN_VERIFICATION) {
5497                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5498                        }
5499                        alwaysAskList.add(info);
5500                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5501                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5502                        if (DEBUG_DOMAIN_VERIFICATION) {
5503                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5504                        }
5505                        undefinedList.add(info);
5506                    }
5507                }
5508            }
5509
5510            // We'll want to include browser possibilities in a few cases
5511            boolean includeBrowser = false;
5512
5513            // First try to add the "always" resolution(s) for the current user, if any
5514            if (alwaysList.size() > 0) {
5515                result.addAll(alwaysList);
5516            } else {
5517                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5518                result.addAll(undefinedList);
5519                // Maybe add one for the other profile.
5520                if (xpDomainInfo != null && (
5521                        xpDomainInfo.bestDomainVerificationStatus
5522                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5523                    result.add(xpDomainInfo.resolveInfo);
5524                }
5525                includeBrowser = true;
5526            }
5527
5528            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5529            // If there were 'always' entries their preferred order has been set, so we also
5530            // back that off to make the alternatives equivalent
5531            if (alwaysAskList.size() > 0) {
5532                for (ResolveInfo i : result) {
5533                    i.preferredOrder = 0;
5534                }
5535                result.addAll(alwaysAskList);
5536                includeBrowser = true;
5537            }
5538
5539            if (includeBrowser) {
5540                // Also add browsers (all of them or only the default one)
5541                if (DEBUG_DOMAIN_VERIFICATION) {
5542                    Slog.v(TAG, "   ...including browsers in candidate set");
5543                }
5544                if ((matchFlags & MATCH_ALL) != 0) {
5545                    result.addAll(matchAllList);
5546                } else {
5547                    // Browser/generic handling case.  If there's a default browser, go straight
5548                    // to that (but only if there is no other higher-priority match).
5549                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5550                    int maxMatchPrio = 0;
5551                    ResolveInfo defaultBrowserMatch = null;
5552                    final int numCandidates = matchAllList.size();
5553                    for (int n = 0; n < numCandidates; n++) {
5554                        ResolveInfo info = matchAllList.get(n);
5555                        // track the highest overall match priority...
5556                        if (info.priority > maxMatchPrio) {
5557                            maxMatchPrio = info.priority;
5558                        }
5559                        // ...and the highest-priority default browser match
5560                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5561                            if (defaultBrowserMatch == null
5562                                    || (defaultBrowserMatch.priority < info.priority)) {
5563                                if (debug) {
5564                                    Slog.v(TAG, "Considering default browser match " + info);
5565                                }
5566                                defaultBrowserMatch = info;
5567                            }
5568                        }
5569                    }
5570                    if (defaultBrowserMatch != null
5571                            && defaultBrowserMatch.priority >= maxMatchPrio
5572                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5573                    {
5574                        if (debug) {
5575                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5576                        }
5577                        result.add(defaultBrowserMatch);
5578                    } else {
5579                        result.addAll(matchAllList);
5580                    }
5581                }
5582
5583                // If there is nothing selected, add all candidates and remove the ones that the user
5584                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5585                if (result.size() == 0) {
5586                    result.addAll(candidates);
5587                    result.removeAll(neverList);
5588                }
5589            }
5590        }
5591        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5592            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5593                    result.size());
5594            for (ResolveInfo info : result) {
5595                Slog.v(TAG, "  + " + info.activityInfo);
5596            }
5597        }
5598        return result;
5599    }
5600
5601    // Returns a packed value as a long:
5602    //
5603    // high 'int'-sized word: link status: undefined/ask/never/always.
5604    // low 'int'-sized word: relative priority among 'always' results.
5605    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5606        long result = ps.getDomainVerificationStatusForUser(userId);
5607        // if none available, get the master status
5608        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5609            if (ps.getIntentFilterVerificationInfo() != null) {
5610                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5611            }
5612        }
5613        return result;
5614    }
5615
5616    private ResolveInfo querySkipCurrentProfileIntents(
5617            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5618            int flags, int sourceUserId) {
5619        if (matchingFilters != null) {
5620            int size = matchingFilters.size();
5621            for (int i = 0; i < size; i ++) {
5622                CrossProfileIntentFilter filter = matchingFilters.get(i);
5623                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5624                    // Checking if there are activities in the target user that can handle the
5625                    // intent.
5626                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5627                            resolvedType, flags, sourceUserId);
5628                    if (resolveInfo != null) {
5629                        return resolveInfo;
5630                    }
5631                }
5632            }
5633        }
5634        return null;
5635    }
5636
5637    // Return matching ResolveInfo in target user if any.
5638    private ResolveInfo queryCrossProfileIntents(
5639            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5640            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5641        if (matchingFilters != null) {
5642            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5643            // match the same intent. For performance reasons, it is better not to
5644            // run queryIntent twice for the same userId
5645            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5646            int size = matchingFilters.size();
5647            for (int i = 0; i < size; i++) {
5648                CrossProfileIntentFilter filter = matchingFilters.get(i);
5649                int targetUserId = filter.getTargetUserId();
5650                boolean skipCurrentProfile =
5651                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5652                boolean skipCurrentProfileIfNoMatchFound =
5653                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5654                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5655                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5656                    // Checking if there are activities in the target user that can handle the
5657                    // intent.
5658                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5659                            resolvedType, flags, sourceUserId);
5660                    if (resolveInfo != null) return resolveInfo;
5661                    alreadyTriedUserIds.put(targetUserId, true);
5662                }
5663            }
5664        }
5665        return null;
5666    }
5667
5668    /**
5669     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5670     * will forward the intent to the filter's target user.
5671     * Otherwise, returns null.
5672     */
5673    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5674            String resolvedType, int flags, int sourceUserId) {
5675        int targetUserId = filter.getTargetUserId();
5676        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5677                resolvedType, flags, targetUserId);
5678        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5679            // If all the matches in the target profile are suspended, return null.
5680            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5681                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5682                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5683                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5684                            targetUserId);
5685                }
5686            }
5687        }
5688        return null;
5689    }
5690
5691    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5692            int sourceUserId, int targetUserId) {
5693        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5694        long ident = Binder.clearCallingIdentity();
5695        boolean targetIsProfile;
5696        try {
5697            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5698        } finally {
5699            Binder.restoreCallingIdentity(ident);
5700        }
5701        String className;
5702        if (targetIsProfile) {
5703            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5704        } else {
5705            className = FORWARD_INTENT_TO_PARENT;
5706        }
5707        ComponentName forwardingActivityComponentName = new ComponentName(
5708                mAndroidApplication.packageName, className);
5709        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5710                sourceUserId);
5711        if (!targetIsProfile) {
5712            forwardingActivityInfo.showUserIcon = targetUserId;
5713            forwardingResolveInfo.noResourceId = true;
5714        }
5715        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5716        forwardingResolveInfo.priority = 0;
5717        forwardingResolveInfo.preferredOrder = 0;
5718        forwardingResolveInfo.match = 0;
5719        forwardingResolveInfo.isDefault = true;
5720        forwardingResolveInfo.filter = filter;
5721        forwardingResolveInfo.targetUserId = targetUserId;
5722        return forwardingResolveInfo;
5723    }
5724
5725    @Override
5726    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5727            Intent[] specifics, String[] specificTypes, Intent intent,
5728            String resolvedType, int flags, int userId) {
5729        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5730                specificTypes, intent, resolvedType, flags, userId));
5731    }
5732
5733    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5734            Intent[] specifics, String[] specificTypes, Intent intent,
5735            String resolvedType, int flags, int userId) {
5736        if (!sUserManager.exists(userId)) return Collections.emptyList();
5737        flags = updateFlagsForResolve(flags, userId, intent);
5738        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5739                false /* requireFullPermission */, false /* checkShell */,
5740                "query intent activity options");
5741        final String resultsAction = intent.getAction();
5742
5743        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5744                | PackageManager.GET_RESOLVED_FILTER, userId);
5745
5746        if (DEBUG_INTENT_MATCHING) {
5747            Log.v(TAG, "Query " + intent + ": " + results);
5748        }
5749
5750        int specificsPos = 0;
5751        int N;
5752
5753        // todo: note that the algorithm used here is O(N^2).  This
5754        // isn't a problem in our current environment, but if we start running
5755        // into situations where we have more than 5 or 10 matches then this
5756        // should probably be changed to something smarter...
5757
5758        // First we go through and resolve each of the specific items
5759        // that were supplied, taking care of removing any corresponding
5760        // duplicate items in the generic resolve list.
5761        if (specifics != null) {
5762            for (int i=0; i<specifics.length; i++) {
5763                final Intent sintent = specifics[i];
5764                if (sintent == null) {
5765                    continue;
5766                }
5767
5768                if (DEBUG_INTENT_MATCHING) {
5769                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5770                }
5771
5772                String action = sintent.getAction();
5773                if (resultsAction != null && resultsAction.equals(action)) {
5774                    // If this action was explicitly requested, then don't
5775                    // remove things that have it.
5776                    action = null;
5777                }
5778
5779                ResolveInfo ri = null;
5780                ActivityInfo ai = null;
5781
5782                ComponentName comp = sintent.getComponent();
5783                if (comp == null) {
5784                    ri = resolveIntent(
5785                        sintent,
5786                        specificTypes != null ? specificTypes[i] : null,
5787                            flags, userId);
5788                    if (ri == null) {
5789                        continue;
5790                    }
5791                    if (ri == mResolveInfo) {
5792                        // ACK!  Must do something better with this.
5793                    }
5794                    ai = ri.activityInfo;
5795                    comp = new ComponentName(ai.applicationInfo.packageName,
5796                            ai.name);
5797                } else {
5798                    ai = getActivityInfo(comp, flags, userId);
5799                    if (ai == null) {
5800                        continue;
5801                    }
5802                }
5803
5804                // Look for any generic query activities that are duplicates
5805                // of this specific one, and remove them from the results.
5806                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5807                N = results.size();
5808                int j;
5809                for (j=specificsPos; j<N; j++) {
5810                    ResolveInfo sri = results.get(j);
5811                    if ((sri.activityInfo.name.equals(comp.getClassName())
5812                            && sri.activityInfo.applicationInfo.packageName.equals(
5813                                    comp.getPackageName()))
5814                        || (action != null && sri.filter.matchAction(action))) {
5815                        results.remove(j);
5816                        if (DEBUG_INTENT_MATCHING) Log.v(
5817                            TAG, "Removing duplicate item from " + j
5818                            + " due to specific " + specificsPos);
5819                        if (ri == null) {
5820                            ri = sri;
5821                        }
5822                        j--;
5823                        N--;
5824                    }
5825                }
5826
5827                // Add this specific item to its proper place.
5828                if (ri == null) {
5829                    ri = new ResolveInfo();
5830                    ri.activityInfo = ai;
5831                }
5832                results.add(specificsPos, ri);
5833                ri.specificIndex = i;
5834                specificsPos++;
5835            }
5836        }
5837
5838        // Now we go through the remaining generic results and remove any
5839        // duplicate actions that are found here.
5840        N = results.size();
5841        for (int i=specificsPos; i<N-1; i++) {
5842            final ResolveInfo rii = results.get(i);
5843            if (rii.filter == null) {
5844                continue;
5845            }
5846
5847            // Iterate over all of the actions of this result's intent
5848            // filter...  typically this should be just one.
5849            final Iterator<String> it = rii.filter.actionsIterator();
5850            if (it == null) {
5851                continue;
5852            }
5853            while (it.hasNext()) {
5854                final String action = it.next();
5855                if (resultsAction != null && resultsAction.equals(action)) {
5856                    // If this action was explicitly requested, then don't
5857                    // remove things that have it.
5858                    continue;
5859                }
5860                for (int j=i+1; j<N; j++) {
5861                    final ResolveInfo rij = results.get(j);
5862                    if (rij.filter != null && rij.filter.hasAction(action)) {
5863                        results.remove(j);
5864                        if (DEBUG_INTENT_MATCHING) Log.v(
5865                            TAG, "Removing duplicate item from " + j
5866                            + " due to action " + action + " at " + i);
5867                        j--;
5868                        N--;
5869                    }
5870                }
5871            }
5872
5873            // If the caller didn't request filter information, drop it now
5874            // so we don't have to marshall/unmarshall it.
5875            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5876                rii.filter = null;
5877            }
5878        }
5879
5880        // Filter out the caller activity if so requested.
5881        if (caller != null) {
5882            N = results.size();
5883            for (int i=0; i<N; i++) {
5884                ActivityInfo ainfo = results.get(i).activityInfo;
5885                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5886                        && caller.getClassName().equals(ainfo.name)) {
5887                    results.remove(i);
5888                    break;
5889                }
5890            }
5891        }
5892
5893        // If the caller didn't request filter information,
5894        // drop them now so we don't have to
5895        // marshall/unmarshall it.
5896        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5897            N = results.size();
5898            for (int i=0; i<N; i++) {
5899                results.get(i).filter = null;
5900            }
5901        }
5902
5903        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5904        return results;
5905    }
5906
5907    @Override
5908    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5909            String resolvedType, int flags, int userId) {
5910        return new ParceledListSlice<>(
5911                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5912    }
5913
5914    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5915            String resolvedType, int flags, int userId) {
5916        if (!sUserManager.exists(userId)) return Collections.emptyList();
5917        flags = updateFlagsForResolve(flags, userId, intent);
5918        ComponentName comp = intent.getComponent();
5919        if (comp == null) {
5920            if (intent.getSelector() != null) {
5921                intent = intent.getSelector();
5922                comp = intent.getComponent();
5923            }
5924        }
5925        if (comp != null) {
5926            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5927            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5928            if (ai != null) {
5929                ResolveInfo ri = new ResolveInfo();
5930                ri.activityInfo = ai;
5931                list.add(ri);
5932            }
5933            return list;
5934        }
5935
5936        // reader
5937        synchronized (mPackages) {
5938            String pkgName = intent.getPackage();
5939            if (pkgName == null) {
5940                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5941            }
5942            final PackageParser.Package pkg = mPackages.get(pkgName);
5943            if (pkg != null) {
5944                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5945                        userId);
5946            }
5947            return Collections.emptyList();
5948        }
5949    }
5950
5951    @Override
5952    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5953        if (!sUserManager.exists(userId)) return null;
5954        flags = updateFlagsForResolve(flags, userId, intent);
5955        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
5956        if (query != null) {
5957            if (query.size() >= 1) {
5958                // If there is more than one service with the same priority,
5959                // just arbitrarily pick the first one.
5960                return query.get(0);
5961            }
5962        }
5963        return null;
5964    }
5965
5966    @Override
5967    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
5968            String resolvedType, int flags, int userId) {
5969        return new ParceledListSlice<>(
5970                queryIntentServicesInternal(intent, resolvedType, flags, userId));
5971    }
5972
5973    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
5974            String resolvedType, int flags, int userId) {
5975        if (!sUserManager.exists(userId)) return Collections.emptyList();
5976        flags = updateFlagsForResolve(flags, userId, intent);
5977        ComponentName comp = intent.getComponent();
5978        if (comp == null) {
5979            if (intent.getSelector() != null) {
5980                intent = intent.getSelector();
5981                comp = intent.getComponent();
5982            }
5983        }
5984        if (comp != null) {
5985            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5986            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5987            if (si != null) {
5988                final ResolveInfo ri = new ResolveInfo();
5989                ri.serviceInfo = si;
5990                list.add(ri);
5991            }
5992            return list;
5993        }
5994
5995        // reader
5996        synchronized (mPackages) {
5997            String pkgName = intent.getPackage();
5998            if (pkgName == null) {
5999                return mServices.queryIntent(intent, resolvedType, flags, userId);
6000            }
6001            final PackageParser.Package pkg = mPackages.get(pkgName);
6002            if (pkg != null) {
6003                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6004                        userId);
6005            }
6006            return Collections.emptyList();
6007        }
6008    }
6009
6010    @Override
6011    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6012            String resolvedType, int flags, int userId) {
6013        return new ParceledListSlice<>(
6014                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6015    }
6016
6017    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6018            Intent intent, String resolvedType, int flags, int userId) {
6019        if (!sUserManager.exists(userId)) return Collections.emptyList();
6020        flags = updateFlagsForResolve(flags, userId, intent);
6021        ComponentName comp = intent.getComponent();
6022        if (comp == null) {
6023            if (intent.getSelector() != null) {
6024                intent = intent.getSelector();
6025                comp = intent.getComponent();
6026            }
6027        }
6028        if (comp != null) {
6029            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6030            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6031            if (pi != null) {
6032                final ResolveInfo ri = new ResolveInfo();
6033                ri.providerInfo = pi;
6034                list.add(ri);
6035            }
6036            return list;
6037        }
6038
6039        // reader
6040        synchronized (mPackages) {
6041            String pkgName = intent.getPackage();
6042            if (pkgName == null) {
6043                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6044            }
6045            final PackageParser.Package pkg = mPackages.get(pkgName);
6046            if (pkg != null) {
6047                return mProviders.queryIntentForPackage(
6048                        intent, resolvedType, flags, pkg.providers, userId);
6049            }
6050            return Collections.emptyList();
6051        }
6052    }
6053
6054    @Override
6055    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6056        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6057        flags = updateFlagsForPackage(flags, userId, null);
6058        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6059        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6060                true /* requireFullPermission */, false /* checkShell */,
6061                "get installed packages");
6062
6063        // writer
6064        synchronized (mPackages) {
6065            ArrayList<PackageInfo> list;
6066            if (listUninstalled) {
6067                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6068                for (PackageSetting ps : mSettings.mPackages.values()) {
6069                    final PackageInfo pi;
6070                    if (ps.pkg != null) {
6071                        pi = generatePackageInfo(ps, flags, userId);
6072                    } else {
6073                        pi = generatePackageInfo(ps, flags, userId);
6074                    }
6075                    if (pi != null) {
6076                        list.add(pi);
6077                    }
6078                }
6079            } else {
6080                list = new ArrayList<PackageInfo>(mPackages.size());
6081                for (PackageParser.Package p : mPackages.values()) {
6082                    final PackageInfo pi =
6083                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6084                    if (pi != null) {
6085                        list.add(pi);
6086                    }
6087                }
6088            }
6089
6090            return new ParceledListSlice<PackageInfo>(list);
6091        }
6092    }
6093
6094    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6095            String[] permissions, boolean[] tmp, int flags, int userId) {
6096        int numMatch = 0;
6097        final PermissionsState permissionsState = ps.getPermissionsState();
6098        for (int i=0; i<permissions.length; i++) {
6099            final String permission = permissions[i];
6100            if (permissionsState.hasPermission(permission, userId)) {
6101                tmp[i] = true;
6102                numMatch++;
6103            } else {
6104                tmp[i] = false;
6105            }
6106        }
6107        if (numMatch == 0) {
6108            return;
6109        }
6110        final PackageInfo pi;
6111        if (ps.pkg != null) {
6112            pi = generatePackageInfo(ps, flags, userId);
6113        } else {
6114            pi = generatePackageInfo(ps, flags, userId);
6115        }
6116        // The above might return null in cases of uninstalled apps or install-state
6117        // skew across users/profiles.
6118        if (pi != null) {
6119            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6120                if (numMatch == permissions.length) {
6121                    pi.requestedPermissions = permissions;
6122                } else {
6123                    pi.requestedPermissions = new String[numMatch];
6124                    numMatch = 0;
6125                    for (int i=0; i<permissions.length; i++) {
6126                        if (tmp[i]) {
6127                            pi.requestedPermissions[numMatch] = permissions[i];
6128                            numMatch++;
6129                        }
6130                    }
6131                }
6132            }
6133            list.add(pi);
6134        }
6135    }
6136
6137    @Override
6138    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6139            String[] permissions, int flags, int userId) {
6140        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6141        flags = updateFlagsForPackage(flags, userId, permissions);
6142        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6143
6144        // writer
6145        synchronized (mPackages) {
6146            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6147            boolean[] tmpBools = new boolean[permissions.length];
6148            if (listUninstalled) {
6149                for (PackageSetting ps : mSettings.mPackages.values()) {
6150                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6151                }
6152            } else {
6153                for (PackageParser.Package pkg : mPackages.values()) {
6154                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6155                    if (ps != null) {
6156                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6157                                userId);
6158                    }
6159                }
6160            }
6161
6162            return new ParceledListSlice<PackageInfo>(list);
6163        }
6164    }
6165
6166    @Override
6167    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6168        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6169        flags = updateFlagsForApplication(flags, userId, null);
6170        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6171
6172        // writer
6173        synchronized (mPackages) {
6174            ArrayList<ApplicationInfo> list;
6175            if (listUninstalled) {
6176                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6177                for (PackageSetting ps : mSettings.mPackages.values()) {
6178                    ApplicationInfo ai;
6179                    if (ps.pkg != null) {
6180                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6181                                ps.readUserState(userId), userId);
6182                    } else {
6183                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6184                    }
6185                    if (ai != null) {
6186                        list.add(ai);
6187                    }
6188                }
6189            } else {
6190                list = new ArrayList<ApplicationInfo>(mPackages.size());
6191                for (PackageParser.Package p : mPackages.values()) {
6192                    if (p.mExtras != null) {
6193                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6194                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6195                        if (ai != null) {
6196                            list.add(ai);
6197                        }
6198                    }
6199                }
6200            }
6201
6202            return new ParceledListSlice<ApplicationInfo>(list);
6203        }
6204    }
6205
6206    @Override
6207    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6208        if (DISABLE_EPHEMERAL_APPS) {
6209            return null;
6210        }
6211
6212        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6213                "getEphemeralApplications");
6214        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6215                true /* requireFullPermission */, false /* checkShell */,
6216                "getEphemeralApplications");
6217        synchronized (mPackages) {
6218            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6219                    .getEphemeralApplicationsLPw(userId);
6220            if (ephemeralApps != null) {
6221                return new ParceledListSlice<>(ephemeralApps);
6222            }
6223        }
6224        return null;
6225    }
6226
6227    @Override
6228    public boolean isEphemeralApplication(String packageName, int userId) {
6229        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6230                true /* requireFullPermission */, false /* checkShell */,
6231                "isEphemeral");
6232        if (DISABLE_EPHEMERAL_APPS) {
6233            return false;
6234        }
6235
6236        if (!isCallerSameApp(packageName)) {
6237            return false;
6238        }
6239        synchronized (mPackages) {
6240            PackageParser.Package pkg = mPackages.get(packageName);
6241            if (pkg != null) {
6242                return pkg.applicationInfo.isEphemeralApp();
6243            }
6244        }
6245        return false;
6246    }
6247
6248    @Override
6249    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6250        if (DISABLE_EPHEMERAL_APPS) {
6251            return null;
6252        }
6253
6254        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6255                true /* requireFullPermission */, false /* checkShell */,
6256                "getCookie");
6257        if (!isCallerSameApp(packageName)) {
6258            return null;
6259        }
6260        synchronized (mPackages) {
6261            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6262                    packageName, userId);
6263        }
6264    }
6265
6266    @Override
6267    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6268        if (DISABLE_EPHEMERAL_APPS) {
6269            return true;
6270        }
6271
6272        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6273                true /* requireFullPermission */, true /* checkShell */,
6274                "setCookie");
6275        if (!isCallerSameApp(packageName)) {
6276            return false;
6277        }
6278        synchronized (mPackages) {
6279            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6280                    packageName, cookie, userId);
6281        }
6282    }
6283
6284    @Override
6285    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6286        if (DISABLE_EPHEMERAL_APPS) {
6287            return null;
6288        }
6289
6290        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6291                "getEphemeralApplicationIcon");
6292        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6293                true /* requireFullPermission */, false /* checkShell */,
6294                "getEphemeralApplicationIcon");
6295        synchronized (mPackages) {
6296            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6297                    packageName, userId);
6298        }
6299    }
6300
6301    private boolean isCallerSameApp(String packageName) {
6302        PackageParser.Package pkg = mPackages.get(packageName);
6303        return pkg != null
6304                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6305    }
6306
6307    @Override
6308    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6309        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6310    }
6311
6312    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6313        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6314
6315        // reader
6316        synchronized (mPackages) {
6317            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6318            final int userId = UserHandle.getCallingUserId();
6319            while (i.hasNext()) {
6320                final PackageParser.Package p = i.next();
6321                if (p.applicationInfo == null) continue;
6322
6323                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6324                        && !p.applicationInfo.isDirectBootAware();
6325                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6326                        && p.applicationInfo.isDirectBootAware();
6327
6328                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6329                        && (!mSafeMode || isSystemApp(p))
6330                        && (matchesUnaware || matchesAware)) {
6331                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6332                    if (ps != null) {
6333                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6334                                ps.readUserState(userId), userId);
6335                        if (ai != null) {
6336                            finalList.add(ai);
6337                        }
6338                    }
6339                }
6340            }
6341        }
6342
6343        return finalList;
6344    }
6345
6346    @Override
6347    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6348        if (!sUserManager.exists(userId)) return null;
6349        flags = updateFlagsForComponent(flags, userId, name);
6350        // reader
6351        synchronized (mPackages) {
6352            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6353            PackageSetting ps = provider != null
6354                    ? mSettings.mPackages.get(provider.owner.packageName)
6355                    : null;
6356            return ps != null
6357                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6358                    ? PackageParser.generateProviderInfo(provider, flags,
6359                            ps.readUserState(userId), userId)
6360                    : null;
6361        }
6362    }
6363
6364    /**
6365     * @deprecated
6366     */
6367    @Deprecated
6368    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6369        // reader
6370        synchronized (mPackages) {
6371            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6372                    .entrySet().iterator();
6373            final int userId = UserHandle.getCallingUserId();
6374            while (i.hasNext()) {
6375                Map.Entry<String, PackageParser.Provider> entry = i.next();
6376                PackageParser.Provider p = entry.getValue();
6377                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6378
6379                if (ps != null && p.syncable
6380                        && (!mSafeMode || (p.info.applicationInfo.flags
6381                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6382                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6383                            ps.readUserState(userId), userId);
6384                    if (info != null) {
6385                        outNames.add(entry.getKey());
6386                        outInfo.add(info);
6387                    }
6388                }
6389            }
6390        }
6391    }
6392
6393    @Override
6394    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6395            int uid, int flags) {
6396        final int userId = processName != null ? UserHandle.getUserId(uid)
6397                : UserHandle.getCallingUserId();
6398        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6399        flags = updateFlagsForComponent(flags, userId, processName);
6400
6401        ArrayList<ProviderInfo> finalList = null;
6402        // reader
6403        synchronized (mPackages) {
6404            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6405            while (i.hasNext()) {
6406                final PackageParser.Provider p = i.next();
6407                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6408                if (ps != null && p.info.authority != null
6409                        && (processName == null
6410                                || (p.info.processName.equals(processName)
6411                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6412                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6413                    if (finalList == null) {
6414                        finalList = new ArrayList<ProviderInfo>(3);
6415                    }
6416                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6417                            ps.readUserState(userId), userId);
6418                    if (info != null) {
6419                        finalList.add(info);
6420                    }
6421                }
6422            }
6423        }
6424
6425        if (finalList != null) {
6426            Collections.sort(finalList, mProviderInitOrderSorter);
6427            return new ParceledListSlice<ProviderInfo>(finalList);
6428        }
6429
6430        return ParceledListSlice.emptyList();
6431    }
6432
6433    @Override
6434    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6435        // reader
6436        synchronized (mPackages) {
6437            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6438            return PackageParser.generateInstrumentationInfo(i, flags);
6439        }
6440    }
6441
6442    @Override
6443    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6444            String targetPackage, int flags) {
6445        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6446    }
6447
6448    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6449            int flags) {
6450        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6451
6452        // reader
6453        synchronized (mPackages) {
6454            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6455            while (i.hasNext()) {
6456                final PackageParser.Instrumentation p = i.next();
6457                if (targetPackage == null
6458                        || targetPackage.equals(p.info.targetPackage)) {
6459                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6460                            flags);
6461                    if (ii != null) {
6462                        finalList.add(ii);
6463                    }
6464                }
6465            }
6466        }
6467
6468        return finalList;
6469    }
6470
6471    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6472        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6473        if (overlays == null) {
6474            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6475            return;
6476        }
6477        for (PackageParser.Package opkg : overlays.values()) {
6478            // Not much to do if idmap fails: we already logged the error
6479            // and we certainly don't want to abort installation of pkg simply
6480            // because an overlay didn't fit properly. For these reasons,
6481            // ignore the return value of createIdmapForPackagePairLI.
6482            createIdmapForPackagePairLI(pkg, opkg);
6483        }
6484    }
6485
6486    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6487            PackageParser.Package opkg) {
6488        if (!opkg.mTrustedOverlay) {
6489            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6490                    opkg.baseCodePath + ": overlay not trusted");
6491            return false;
6492        }
6493        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6494        if (overlaySet == null) {
6495            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6496                    opkg.baseCodePath + " but target package has no known overlays");
6497            return false;
6498        }
6499        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6500        // TODO: generate idmap for split APKs
6501        try {
6502            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6503        } catch (InstallerException e) {
6504            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6505                    + opkg.baseCodePath);
6506            return false;
6507        }
6508        PackageParser.Package[] overlayArray =
6509            overlaySet.values().toArray(new PackageParser.Package[0]);
6510        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6511            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6512                return p1.mOverlayPriority - p2.mOverlayPriority;
6513            }
6514        };
6515        Arrays.sort(overlayArray, cmp);
6516
6517        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6518        int i = 0;
6519        for (PackageParser.Package p : overlayArray) {
6520            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6521        }
6522        return true;
6523    }
6524
6525    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6526        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6527        try {
6528            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6529        } finally {
6530            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6531        }
6532    }
6533
6534    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6535        final File[] files = dir.listFiles();
6536        if (ArrayUtils.isEmpty(files)) {
6537            Log.d(TAG, "No files in app dir " + dir);
6538            return;
6539        }
6540
6541        if (DEBUG_PACKAGE_SCANNING) {
6542            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6543                    + " flags=0x" + Integer.toHexString(parseFlags));
6544        }
6545
6546        for (File file : files) {
6547            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6548                    && !PackageInstallerService.isStageName(file.getName());
6549            if (!isPackage) {
6550                // Ignore entries which are not packages
6551                continue;
6552            }
6553            try {
6554                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6555                        scanFlags, currentTime, null);
6556            } catch (PackageManagerException e) {
6557                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6558
6559                // Delete invalid userdata apps
6560                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6561                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6562                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6563                    removeCodePathLI(file);
6564                }
6565            }
6566        }
6567    }
6568
6569    private static File getSettingsProblemFile() {
6570        File dataDir = Environment.getDataDirectory();
6571        File systemDir = new File(dataDir, "system");
6572        File fname = new File(systemDir, "uiderrors.txt");
6573        return fname;
6574    }
6575
6576    static void reportSettingsProblem(int priority, String msg) {
6577        logCriticalInfo(priority, msg);
6578    }
6579
6580    static void logCriticalInfo(int priority, String msg) {
6581        Slog.println(priority, TAG, msg);
6582        EventLogTags.writePmCriticalInfo(msg);
6583        try {
6584            File fname = getSettingsProblemFile();
6585            FileOutputStream out = new FileOutputStream(fname, true);
6586            PrintWriter pw = new FastPrintWriter(out);
6587            SimpleDateFormat formatter = new SimpleDateFormat();
6588            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6589            pw.println(dateString + ": " + msg);
6590            pw.close();
6591            FileUtils.setPermissions(
6592                    fname.toString(),
6593                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6594                    -1, -1);
6595        } catch (java.io.IOException e) {
6596        }
6597    }
6598
6599    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6600        if (srcFile.isDirectory()) {
6601            final File baseFile = new File(pkg.baseCodePath);
6602            long maxModifiedTime = baseFile.lastModified();
6603            if (pkg.splitCodePaths != null) {
6604                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6605                    final File splitFile = new File(pkg.splitCodePaths[i]);
6606                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6607                }
6608            }
6609            return maxModifiedTime;
6610        }
6611        return srcFile.lastModified();
6612    }
6613
6614    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6615            final int policyFlags) throws PackageManagerException {
6616        if (ps != null
6617                && ps.codePath.equals(srcFile)
6618                && ps.timeStamp == getLastModifiedTime(pkg, srcFile)
6619                && !isCompatSignatureUpdateNeeded(pkg)
6620                && !isRecoverSignatureUpdateNeeded(pkg)) {
6621            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6622            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6623            ArraySet<PublicKey> signingKs;
6624            synchronized (mPackages) {
6625                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6626            }
6627            if (ps.signatures.mSignatures != null
6628                    && ps.signatures.mSignatures.length != 0
6629                    && signingKs != null) {
6630                // Optimization: reuse the existing cached certificates
6631                // if the package appears to be unchanged.
6632                pkg.mSignatures = ps.signatures.mSignatures;
6633                pkg.mSigningKeys = signingKs;
6634                return;
6635            }
6636
6637            Slog.w(TAG, "PackageSetting for " + ps.name
6638                    + " is missing signatures.  Collecting certs again to recover them.");
6639        } else {
6640            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6641        }
6642
6643        try {
6644            PackageParser.collectCertificates(pkg, policyFlags);
6645        } catch (PackageParserException e) {
6646            throw PackageManagerException.from(e);
6647        }
6648    }
6649
6650    /**
6651     *  Traces a package scan.
6652     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6653     */
6654    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6655            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6656        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6657        try {
6658            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6659        } finally {
6660            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6661        }
6662    }
6663
6664    /**
6665     *  Scans a package and returns the newly parsed package.
6666     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6667     */
6668    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6669            long currentTime, UserHandle user) throws PackageManagerException {
6670        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6671        PackageParser pp = new PackageParser();
6672        pp.setSeparateProcesses(mSeparateProcesses);
6673        pp.setOnlyCoreApps(mOnlyCore);
6674        pp.setDisplayMetrics(mMetrics);
6675
6676        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6677            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6678        }
6679
6680        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6681        final PackageParser.Package pkg;
6682        try {
6683            pkg = pp.parsePackage(scanFile, parseFlags);
6684        } catch (PackageParserException e) {
6685            throw PackageManagerException.from(e);
6686        } finally {
6687            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6688        }
6689
6690        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6691    }
6692
6693    /**
6694     *  Scans a package and returns the newly parsed package.
6695     *  @throws PackageManagerException on a parse error.
6696     */
6697    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6698            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6699            throws PackageManagerException {
6700        // If the package has children and this is the first dive in the function
6701        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6702        // packages (parent and children) would be successfully scanned before the
6703        // actual scan since scanning mutates internal state and we want to atomically
6704        // install the package and its children.
6705        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6706            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6707                scanFlags |= SCAN_CHECK_ONLY;
6708            }
6709        } else {
6710            scanFlags &= ~SCAN_CHECK_ONLY;
6711        }
6712
6713        // Scan the parent
6714        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6715                scanFlags, currentTime, user);
6716
6717        // Scan the children
6718        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6719        for (int i = 0; i < childCount; i++) {
6720            PackageParser.Package childPackage = pkg.childPackages.get(i);
6721            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6722                    currentTime, user);
6723        }
6724
6725
6726        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6727            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6728        }
6729
6730        return scannedPkg;
6731    }
6732
6733    /**
6734     *  Scans a package and returns the newly parsed package.
6735     *  @throws PackageManagerException on a parse error.
6736     */
6737    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6738            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6739            throws PackageManagerException {
6740        PackageSetting ps = null;
6741        PackageSetting updatedPkg;
6742        // reader
6743        synchronized (mPackages) {
6744            // Look to see if we already know about this package.
6745            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6746            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6747                // This package has been renamed to its original name.  Let's
6748                // use that.
6749                ps = mSettings.peekPackageLPr(oldName);
6750            }
6751            // If there was no original package, see one for the real package name.
6752            if (ps == null) {
6753                ps = mSettings.peekPackageLPr(pkg.packageName);
6754            }
6755            // Check to see if this package could be hiding/updating a system
6756            // package.  Must look for it either under the original or real
6757            // package name depending on our state.
6758            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6759            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6760
6761            // If this is a package we don't know about on the system partition, we
6762            // may need to remove disabled child packages on the system partition
6763            // or may need to not add child packages if the parent apk is updated
6764            // on the data partition and no longer defines this child package.
6765            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6766                // If this is a parent package for an updated system app and this system
6767                // app got an OTA update which no longer defines some of the child packages
6768                // we have to prune them from the disabled system packages.
6769                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6770                if (disabledPs != null) {
6771                    final int scannedChildCount = (pkg.childPackages != null)
6772                            ? pkg.childPackages.size() : 0;
6773                    final int disabledChildCount = disabledPs.childPackageNames != null
6774                            ? disabledPs.childPackageNames.size() : 0;
6775                    for (int i = 0; i < disabledChildCount; i++) {
6776                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6777                        boolean disabledPackageAvailable = false;
6778                        for (int j = 0; j < scannedChildCount; j++) {
6779                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6780                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6781                                disabledPackageAvailable = true;
6782                                break;
6783                            }
6784                         }
6785                         if (!disabledPackageAvailable) {
6786                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6787                         }
6788                    }
6789                }
6790            }
6791        }
6792
6793        boolean updatedPkgBetter = false;
6794        // First check if this is a system package that may involve an update
6795        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6796            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6797            // it needs to drop FLAG_PRIVILEGED.
6798            if (locationIsPrivileged(scanFile)) {
6799                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6800            } else {
6801                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6802            }
6803
6804            if (ps != null && !ps.codePath.equals(scanFile)) {
6805                // The path has changed from what was last scanned...  check the
6806                // version of the new path against what we have stored to determine
6807                // what to do.
6808                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6809                if (pkg.mVersionCode <= ps.versionCode) {
6810                    // The system package has been updated and the code path does not match
6811                    // Ignore entry. Skip it.
6812                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6813                            + " ignored: updated version " + ps.versionCode
6814                            + " better than this " + pkg.mVersionCode);
6815                    if (!updatedPkg.codePath.equals(scanFile)) {
6816                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6817                                + ps.name + " changing from " + updatedPkg.codePathString
6818                                + " to " + scanFile);
6819                        updatedPkg.codePath = scanFile;
6820                        updatedPkg.codePathString = scanFile.toString();
6821                        updatedPkg.resourcePath = scanFile;
6822                        updatedPkg.resourcePathString = scanFile.toString();
6823                    }
6824                    updatedPkg.pkg = pkg;
6825                    updatedPkg.versionCode = pkg.mVersionCode;
6826
6827                    // Update the disabled system child packages to point to the package too.
6828                    final int childCount = updatedPkg.childPackageNames != null
6829                            ? updatedPkg.childPackageNames.size() : 0;
6830                    for (int i = 0; i < childCount; i++) {
6831                        String childPackageName = updatedPkg.childPackageNames.get(i);
6832                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6833                                childPackageName);
6834                        if (updatedChildPkg != null) {
6835                            updatedChildPkg.pkg = pkg;
6836                            updatedChildPkg.versionCode = pkg.mVersionCode;
6837                        }
6838                    }
6839
6840                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6841                            + scanFile + " ignored: updated version " + ps.versionCode
6842                            + " better than this " + pkg.mVersionCode);
6843                } else {
6844                    // The current app on the system partition is better than
6845                    // what we have updated to on the data partition; switch
6846                    // back to the system partition version.
6847                    // At this point, its safely assumed that package installation for
6848                    // apps in system partition will go through. If not there won't be a working
6849                    // version of the app
6850                    // writer
6851                    synchronized (mPackages) {
6852                        // Just remove the loaded entries from package lists.
6853                        mPackages.remove(ps.name);
6854                    }
6855
6856                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6857                            + " reverting from " + ps.codePathString
6858                            + ": new version " + pkg.mVersionCode
6859                            + " better than installed " + ps.versionCode);
6860
6861                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6862                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6863                    synchronized (mInstallLock) {
6864                        args.cleanUpResourcesLI();
6865                    }
6866                    synchronized (mPackages) {
6867                        mSettings.enableSystemPackageLPw(ps.name);
6868                    }
6869                    updatedPkgBetter = true;
6870                }
6871            }
6872        }
6873
6874        if (updatedPkg != null) {
6875            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6876            // initially
6877            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6878
6879            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6880            // flag set initially
6881            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6882                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6883            }
6884        }
6885
6886        // Verify certificates against what was last scanned
6887        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6888
6889        /*
6890         * A new system app appeared, but we already had a non-system one of the
6891         * same name installed earlier.
6892         */
6893        boolean shouldHideSystemApp = false;
6894        if (updatedPkg == null && ps != null
6895                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6896            /*
6897             * Check to make sure the signatures match first. If they don't,
6898             * wipe the installed application and its data.
6899             */
6900            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6901                    != PackageManager.SIGNATURE_MATCH) {
6902                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6903                        + " signatures don't match existing userdata copy; removing");
6904                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6905                        "scanPackageInternalLI")) {
6906                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6907                }
6908                ps = null;
6909            } else {
6910                /*
6911                 * If the newly-added system app is an older version than the
6912                 * already installed version, hide it. It will be scanned later
6913                 * and re-added like an update.
6914                 */
6915                if (pkg.mVersionCode <= ps.versionCode) {
6916                    shouldHideSystemApp = true;
6917                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6918                            + " but new version " + pkg.mVersionCode + " better than installed "
6919                            + ps.versionCode + "; hiding system");
6920                } else {
6921                    /*
6922                     * The newly found system app is a newer version that the
6923                     * one previously installed. Simply remove the
6924                     * already-installed application and replace it with our own
6925                     * while keeping the application data.
6926                     */
6927                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6928                            + " reverting from " + ps.codePathString + ": new version "
6929                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6930                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6931                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6932                    synchronized (mInstallLock) {
6933                        args.cleanUpResourcesLI();
6934                    }
6935                }
6936            }
6937        }
6938
6939        // The apk is forward locked (not public) if its code and resources
6940        // are kept in different files. (except for app in either system or
6941        // vendor path).
6942        // TODO grab this value from PackageSettings
6943        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6944            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6945                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
6946            }
6947        }
6948
6949        // TODO: extend to support forward-locked splits
6950        String resourcePath = null;
6951        String baseResourcePath = null;
6952        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6953            if (ps != null && ps.resourcePathString != null) {
6954                resourcePath = ps.resourcePathString;
6955                baseResourcePath = ps.resourcePathString;
6956            } else {
6957                // Should not happen at all. Just log an error.
6958                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6959            }
6960        } else {
6961            resourcePath = pkg.codePath;
6962            baseResourcePath = pkg.baseCodePath;
6963        }
6964
6965        // Set application objects path explicitly.
6966        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6967        pkg.setApplicationInfoCodePath(pkg.codePath);
6968        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6969        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6970        pkg.setApplicationInfoResourcePath(resourcePath);
6971        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6972        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6973
6974        // Note that we invoke the following method only if we are about to unpack an application
6975        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
6976                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6977
6978        /*
6979         * If the system app should be overridden by a previously installed
6980         * data, hide the system app now and let the /data/app scan pick it up
6981         * again.
6982         */
6983        if (shouldHideSystemApp) {
6984            synchronized (mPackages) {
6985                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6986            }
6987        }
6988
6989        return scannedPkg;
6990    }
6991
6992    private static String fixProcessName(String defProcessName,
6993            String processName, int uid) {
6994        if (processName == null) {
6995            return defProcessName;
6996        }
6997        return processName;
6998    }
6999
7000    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7001            throws PackageManagerException {
7002        if (pkgSetting.signatures.mSignatures != null) {
7003            // Already existing package. Make sure signatures match
7004            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7005                    == PackageManager.SIGNATURE_MATCH;
7006            if (!match) {
7007                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7008                        == PackageManager.SIGNATURE_MATCH;
7009            }
7010            if (!match) {
7011                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7012                        == PackageManager.SIGNATURE_MATCH;
7013            }
7014            if (!match) {
7015                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7016                        + pkg.packageName + " signatures do not match the "
7017                        + "previously installed version; ignoring!");
7018            }
7019        }
7020
7021        // Check for shared user signatures
7022        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7023            // Already existing package. Make sure signatures match
7024            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7025                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7026            if (!match) {
7027                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7028                        == PackageManager.SIGNATURE_MATCH;
7029            }
7030            if (!match) {
7031                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7032                        == PackageManager.SIGNATURE_MATCH;
7033            }
7034            if (!match) {
7035                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7036                        "Package " + pkg.packageName
7037                        + " has no signatures that match those in shared user "
7038                        + pkgSetting.sharedUser.name + "; ignoring!");
7039            }
7040        }
7041    }
7042
7043    /**
7044     * Enforces that only the system UID or root's UID can call a method exposed
7045     * via Binder.
7046     *
7047     * @param message used as message if SecurityException is thrown
7048     * @throws SecurityException if the caller is not system or root
7049     */
7050    private static final void enforceSystemOrRoot(String message) {
7051        final int uid = Binder.getCallingUid();
7052        if (uid != Process.SYSTEM_UID && uid != 0) {
7053            throw new SecurityException(message);
7054        }
7055    }
7056
7057    @Override
7058    public void performFstrimIfNeeded() {
7059        enforceSystemOrRoot("Only the system can request fstrim");
7060
7061        // Before everything else, see whether we need to fstrim.
7062        try {
7063            IMountService ms = PackageHelper.getMountService();
7064            if (ms != null) {
7065                boolean doTrim = false;
7066                final long interval = android.provider.Settings.Global.getLong(
7067                        mContext.getContentResolver(),
7068                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7069                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7070                if (interval > 0) {
7071                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7072                    if (timeSinceLast > interval) {
7073                        doTrim = true;
7074                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7075                                + "; running immediately");
7076                    }
7077                }
7078                if (doTrim) {
7079                    if (!isFirstBoot()) {
7080                        try {
7081                            ActivityManagerNative.getDefault().showBootMessage(
7082                                    mContext.getResources().getString(
7083                                            R.string.android_upgrading_fstrim), true);
7084                        } catch (RemoteException e) {
7085                        }
7086                    }
7087                    ms.runMaintenance();
7088                }
7089            } else {
7090                Slog.e(TAG, "Mount service unavailable!");
7091            }
7092        } catch (RemoteException e) {
7093            // Can't happen; MountService is local
7094        }
7095    }
7096
7097    @Override
7098    public void updatePackagesIfNeeded() {
7099        enforceSystemOrRoot("Only the system can request package update");
7100
7101        // We need to re-extract after an OTA.
7102        boolean causeUpgrade = isUpgrade();
7103
7104        // First boot or factory reset.
7105        // Note: we also handle devices that are upgrading to N right now as if it is their
7106        //       first boot, as they do not have profile data.
7107        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7108
7109        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7110        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7111
7112        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7113            return;
7114        }
7115
7116        List<PackageParser.Package> pkgs;
7117        synchronized (mPackages) {
7118            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7119        }
7120
7121        final long startTime = System.nanoTime();
7122        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7123                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7124
7125        final int elapsedTimeSeconds =
7126                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7127
7128        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7129        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7130        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7131        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7132        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7133    }
7134
7135    /**
7136     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7137     * containing statistics about the invocation. The array consists of three elements,
7138     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7139     * and {@code numberOfPackagesFailed}.
7140     */
7141    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7142            String compilerFilter) {
7143
7144        int numberOfPackagesVisited = 0;
7145        int numberOfPackagesOptimized = 0;
7146        int numberOfPackagesSkipped = 0;
7147        int numberOfPackagesFailed = 0;
7148        final int numberOfPackagesToDexopt = pkgs.size();
7149
7150        for (PackageParser.Package pkg : pkgs) {
7151            numberOfPackagesVisited++;
7152
7153            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7154                if (DEBUG_DEXOPT) {
7155                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7156                }
7157                numberOfPackagesSkipped++;
7158                continue;
7159            }
7160
7161            if (DEBUG_DEXOPT) {
7162                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7163                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7164            }
7165
7166            if (showDialog) {
7167                try {
7168                    ActivityManagerNative.getDefault().showBootMessage(
7169                            mContext.getResources().getString(R.string.android_upgrading_apk,
7170                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7171                } catch (RemoteException e) {
7172                }
7173            }
7174
7175            // If the OTA updates a system app which was previously preopted to a non-preopted state
7176            // the app might end up being verified at runtime. That's because by default the apps
7177            // are verify-profile but for preopted apps there's no profile.
7178            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7179            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7180            // filter (by default interpret-only).
7181            // Note that at this stage unused apps are already filtered.
7182            if (isSystemApp(pkg) &&
7183                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7184                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7185                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7186            }
7187
7188            // checkProfiles is false to avoid merging profiles during boot which
7189            // might interfere with background compilation (b/28612421).
7190            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7191            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7192            // trade-off worth doing to save boot time work.
7193            int dexOptStatus = performDexOptTraced(pkg.packageName,
7194                    false /* checkProfiles */,
7195                    compilerFilter,
7196                    false /* force */);
7197            switch (dexOptStatus) {
7198                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7199                    numberOfPackagesOptimized++;
7200                    break;
7201                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7202                    numberOfPackagesSkipped++;
7203                    break;
7204                case PackageDexOptimizer.DEX_OPT_FAILED:
7205                    numberOfPackagesFailed++;
7206                    break;
7207                default:
7208                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7209                    break;
7210            }
7211        }
7212
7213        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7214                numberOfPackagesFailed };
7215    }
7216
7217    @Override
7218    public void notifyPackageUse(String packageName, int reason) {
7219        synchronized (mPackages) {
7220            PackageParser.Package p = mPackages.get(packageName);
7221            if (p == null) {
7222                return;
7223            }
7224            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7225        }
7226    }
7227
7228    // TODO: this is not used nor needed. Delete it.
7229    @Override
7230    public boolean performDexOptIfNeeded(String packageName) {
7231        int dexOptStatus = performDexOptTraced(packageName,
7232                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7233        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7234    }
7235
7236    @Override
7237    public boolean performDexOpt(String packageName,
7238            boolean checkProfiles, int compileReason, boolean force) {
7239        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7240                getCompilerFilterForReason(compileReason), force);
7241        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7242    }
7243
7244    @Override
7245    public boolean performDexOptMode(String packageName,
7246            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7247        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7248                targetCompilerFilter, force);
7249        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7250    }
7251
7252    private int performDexOptTraced(String packageName,
7253                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7254        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7255        try {
7256            return performDexOptInternal(packageName, checkProfiles,
7257                    targetCompilerFilter, force);
7258        } finally {
7259            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7260        }
7261    }
7262
7263    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7264    // if the package can now be considered up to date for the given filter.
7265    private int performDexOptInternal(String packageName,
7266                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7267        PackageParser.Package p;
7268        synchronized (mPackages) {
7269            p = mPackages.get(packageName);
7270            if (p == null) {
7271                // Package could not be found. Report failure.
7272                return PackageDexOptimizer.DEX_OPT_FAILED;
7273            }
7274            mPackageUsage.maybeWriteAsync(mPackages);
7275            mCompilerStats.maybeWriteAsync();
7276        }
7277        long callingId = Binder.clearCallingIdentity();
7278        try {
7279            synchronized (mInstallLock) {
7280                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7281                        targetCompilerFilter, force);
7282            }
7283        } finally {
7284            Binder.restoreCallingIdentity(callingId);
7285        }
7286    }
7287
7288    public ArraySet<String> getOptimizablePackages() {
7289        ArraySet<String> pkgs = new ArraySet<String>();
7290        synchronized (mPackages) {
7291            for (PackageParser.Package p : mPackages.values()) {
7292                if (PackageDexOptimizer.canOptimizePackage(p)) {
7293                    pkgs.add(p.packageName);
7294                }
7295            }
7296        }
7297        return pkgs;
7298    }
7299
7300    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7301            boolean checkProfiles, String targetCompilerFilter,
7302            boolean force) {
7303        // Select the dex optimizer based on the force parameter.
7304        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7305        //       allocate an object here.
7306        PackageDexOptimizer pdo = force
7307                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7308                : mPackageDexOptimizer;
7309
7310        // Optimize all dependencies first. Note: we ignore the return value and march on
7311        // on errors.
7312        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7313        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7314        if (!deps.isEmpty()) {
7315            for (PackageParser.Package depPackage : deps) {
7316                // TODO: Analyze and investigate if we (should) profile libraries.
7317                // Currently this will do a full compilation of the library by default.
7318                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7319                        false /* checkProfiles */,
7320                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7321                        getOrCreateCompilerPackageStats(depPackage));
7322            }
7323        }
7324        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7325                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7326    }
7327
7328    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7329        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7330            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7331            Set<String> collectedNames = new HashSet<>();
7332            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7333
7334            retValue.remove(p);
7335
7336            return retValue;
7337        } else {
7338            return Collections.emptyList();
7339        }
7340    }
7341
7342    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7343            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7344        if (!collectedNames.contains(p.packageName)) {
7345            collectedNames.add(p.packageName);
7346            collected.add(p);
7347
7348            if (p.usesLibraries != null) {
7349                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7350            }
7351            if (p.usesOptionalLibraries != null) {
7352                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7353                        collectedNames);
7354            }
7355        }
7356    }
7357
7358    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7359            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7360        for (String libName : libs) {
7361            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7362            if (libPkg != null) {
7363                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7364            }
7365        }
7366    }
7367
7368    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7369        synchronized (mPackages) {
7370            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7371            if (lib != null && lib.apk != null) {
7372                return mPackages.get(lib.apk);
7373            }
7374        }
7375        return null;
7376    }
7377
7378    public void shutdown() {
7379        mPackageUsage.writeNow(mPackages);
7380        mCompilerStats.writeNow();
7381    }
7382
7383    @Override
7384    public void dumpProfiles(String packageName) {
7385        PackageParser.Package pkg;
7386        synchronized (mPackages) {
7387            pkg = mPackages.get(packageName);
7388            if (pkg == null) {
7389                throw new IllegalArgumentException("Unknown package: " + packageName);
7390            }
7391        }
7392        /* Only the shell, root, or the app user should be able to dump profiles. */
7393        int callingUid = Binder.getCallingUid();
7394        if (callingUid != Process.SHELL_UID &&
7395            callingUid != Process.ROOT_UID &&
7396            callingUid != pkg.applicationInfo.uid) {
7397            throw new SecurityException("dumpProfiles");
7398        }
7399
7400        synchronized (mInstallLock) {
7401            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7402            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7403            try {
7404                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7405                String gid = Integer.toString(sharedGid);
7406                String codePaths = TextUtils.join(";", allCodePaths);
7407                mInstaller.dumpProfiles(gid, packageName, codePaths);
7408            } catch (InstallerException e) {
7409                Slog.w(TAG, "Failed to dump profiles", e);
7410            }
7411            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7412        }
7413    }
7414
7415    @Override
7416    public void forceDexOpt(String packageName) {
7417        enforceSystemOrRoot("forceDexOpt");
7418
7419        PackageParser.Package pkg;
7420        synchronized (mPackages) {
7421            pkg = mPackages.get(packageName);
7422            if (pkg == null) {
7423                throw new IllegalArgumentException("Unknown package: " + packageName);
7424            }
7425        }
7426
7427        synchronized (mInstallLock) {
7428            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7429
7430            // Whoever is calling forceDexOpt wants a fully compiled package.
7431            // Don't use profiles since that may cause compilation to be skipped.
7432            final int res = performDexOptInternalWithDependenciesLI(pkg,
7433                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7434                    true /* force */);
7435
7436            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7437            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7438                throw new IllegalStateException("Failed to dexopt: " + res);
7439            }
7440        }
7441    }
7442
7443    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7444        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7445            Slog.w(TAG, "Unable to update from " + oldPkg.name
7446                    + " to " + newPkg.packageName
7447                    + ": old package not in system partition");
7448            return false;
7449        } else if (mPackages.get(oldPkg.name) != null) {
7450            Slog.w(TAG, "Unable to update from " + oldPkg.name
7451                    + " to " + newPkg.packageName
7452                    + ": old package still exists");
7453            return false;
7454        }
7455        return true;
7456    }
7457
7458    void removeCodePathLI(File codePath) {
7459        if (codePath.isDirectory()) {
7460            try {
7461                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7462            } catch (InstallerException e) {
7463                Slog.w(TAG, "Failed to remove code path", e);
7464            }
7465        } else {
7466            codePath.delete();
7467        }
7468    }
7469
7470    private int[] resolveUserIds(int userId) {
7471        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7472    }
7473
7474    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7475        if (pkg == null) {
7476            Slog.wtf(TAG, "Package was null!", new Throwable());
7477            return;
7478        }
7479        clearAppDataLeafLIF(pkg, userId, flags);
7480        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7481        for (int i = 0; i < childCount; i++) {
7482            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7483        }
7484    }
7485
7486    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7487        final PackageSetting ps;
7488        synchronized (mPackages) {
7489            ps = mSettings.mPackages.get(pkg.packageName);
7490        }
7491        for (int realUserId : resolveUserIds(userId)) {
7492            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7493            try {
7494                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7495                        ceDataInode);
7496            } catch (InstallerException e) {
7497                Slog.w(TAG, String.valueOf(e));
7498            }
7499        }
7500    }
7501
7502    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7503        if (pkg == null) {
7504            Slog.wtf(TAG, "Package was null!", new Throwable());
7505            return;
7506        }
7507        destroyAppDataLeafLIF(pkg, userId, flags);
7508        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7509        for (int i = 0; i < childCount; i++) {
7510            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7511        }
7512    }
7513
7514    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7515        final PackageSetting ps;
7516        synchronized (mPackages) {
7517            ps = mSettings.mPackages.get(pkg.packageName);
7518        }
7519        for (int realUserId : resolveUserIds(userId)) {
7520            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7521            try {
7522                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7523                        ceDataInode);
7524            } catch (InstallerException e) {
7525                Slog.w(TAG, String.valueOf(e));
7526            }
7527        }
7528    }
7529
7530    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7531        if (pkg == null) {
7532            Slog.wtf(TAG, "Package was null!", new Throwable());
7533            return;
7534        }
7535        destroyAppProfilesLeafLIF(pkg);
7536        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7537        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7538        for (int i = 0; i < childCount; i++) {
7539            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7540            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7541                    true /* removeBaseMarker */);
7542        }
7543    }
7544
7545    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7546            boolean removeBaseMarker) {
7547        if (pkg.isForwardLocked()) {
7548            return;
7549        }
7550
7551        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7552            try {
7553                path = PackageManagerServiceUtils.realpath(new File(path));
7554            } catch (IOException e) {
7555                // TODO: Should we return early here ?
7556                Slog.w(TAG, "Failed to get canonical path", e);
7557                continue;
7558            }
7559
7560            final String useMarker = path.replace('/', '@');
7561            for (int realUserId : resolveUserIds(userId)) {
7562                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7563                if (removeBaseMarker) {
7564                    File foreignUseMark = new File(profileDir, useMarker);
7565                    if (foreignUseMark.exists()) {
7566                        if (!foreignUseMark.delete()) {
7567                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7568                                    + pkg.packageName);
7569                        }
7570                    }
7571                }
7572
7573                File[] markers = profileDir.listFiles();
7574                if (markers != null) {
7575                    final String searchString = "@" + pkg.packageName + "@";
7576                    // We also delete all markers that contain the package name we're
7577                    // uninstalling. These are associated with secondary dex-files belonging
7578                    // to the package. Reconstructing the path of these dex files is messy
7579                    // in general.
7580                    for (File marker : markers) {
7581                        if (marker.getName().indexOf(searchString) > 0) {
7582                            if (!marker.delete()) {
7583                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7584                                    + pkg.packageName);
7585                            }
7586                        }
7587                    }
7588                }
7589            }
7590        }
7591    }
7592
7593    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7594        try {
7595            mInstaller.destroyAppProfiles(pkg.packageName);
7596        } catch (InstallerException e) {
7597            Slog.w(TAG, String.valueOf(e));
7598        }
7599    }
7600
7601    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7602        if (pkg == null) {
7603            Slog.wtf(TAG, "Package was null!", new Throwable());
7604            return;
7605        }
7606        clearAppProfilesLeafLIF(pkg);
7607        // We don't remove the base foreign use marker when clearing profiles because
7608        // we will rename it when the app is updated. Unlike the actual profile contents,
7609        // the foreign use marker is good across installs.
7610        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7611        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7612        for (int i = 0; i < childCount; i++) {
7613            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7614        }
7615    }
7616
7617    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7618        try {
7619            mInstaller.clearAppProfiles(pkg.packageName);
7620        } catch (InstallerException e) {
7621            Slog.w(TAG, String.valueOf(e));
7622        }
7623    }
7624
7625    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7626            long lastUpdateTime) {
7627        // Set parent install/update time
7628        PackageSetting ps = (PackageSetting) pkg.mExtras;
7629        if (ps != null) {
7630            ps.firstInstallTime = firstInstallTime;
7631            ps.lastUpdateTime = lastUpdateTime;
7632        }
7633        // Set children install/update time
7634        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7635        for (int i = 0; i < childCount; i++) {
7636            PackageParser.Package childPkg = pkg.childPackages.get(i);
7637            ps = (PackageSetting) childPkg.mExtras;
7638            if (ps != null) {
7639                ps.firstInstallTime = firstInstallTime;
7640                ps.lastUpdateTime = lastUpdateTime;
7641            }
7642        }
7643    }
7644
7645    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7646            PackageParser.Package changingLib) {
7647        if (file.path != null) {
7648            usesLibraryFiles.add(file.path);
7649            return;
7650        }
7651        PackageParser.Package p = mPackages.get(file.apk);
7652        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7653            // If we are doing this while in the middle of updating a library apk,
7654            // then we need to make sure to use that new apk for determining the
7655            // dependencies here.  (We haven't yet finished committing the new apk
7656            // to the package manager state.)
7657            if (p == null || p.packageName.equals(changingLib.packageName)) {
7658                p = changingLib;
7659            }
7660        }
7661        if (p != null) {
7662            usesLibraryFiles.addAll(p.getAllCodePaths());
7663        }
7664    }
7665
7666    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7667            PackageParser.Package changingLib) throws PackageManagerException {
7668        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7669            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7670            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7671            for (int i=0; i<N; i++) {
7672                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7673                if (file == null) {
7674                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7675                            "Package " + pkg.packageName + " requires unavailable shared library "
7676                            + pkg.usesLibraries.get(i) + "; failing!");
7677                }
7678                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7679            }
7680            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7681            for (int i=0; i<N; i++) {
7682                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7683                if (file == null) {
7684                    Slog.w(TAG, "Package " + pkg.packageName
7685                            + " desires unavailable shared library "
7686                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7687                } else {
7688                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7689                }
7690            }
7691            N = usesLibraryFiles.size();
7692            if (N > 0) {
7693                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7694            } else {
7695                pkg.usesLibraryFiles = null;
7696            }
7697        }
7698    }
7699
7700    private static boolean hasString(List<String> list, List<String> which) {
7701        if (list == null) {
7702            return false;
7703        }
7704        for (int i=list.size()-1; i>=0; i--) {
7705            for (int j=which.size()-1; j>=0; j--) {
7706                if (which.get(j).equals(list.get(i))) {
7707                    return true;
7708                }
7709            }
7710        }
7711        return false;
7712    }
7713
7714    private void updateAllSharedLibrariesLPw() {
7715        for (PackageParser.Package pkg : mPackages.values()) {
7716            try {
7717                updateSharedLibrariesLPw(pkg, null);
7718            } catch (PackageManagerException e) {
7719                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7720            }
7721        }
7722    }
7723
7724    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7725            PackageParser.Package changingPkg) {
7726        ArrayList<PackageParser.Package> res = null;
7727        for (PackageParser.Package pkg : mPackages.values()) {
7728            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7729                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7730                if (res == null) {
7731                    res = new ArrayList<PackageParser.Package>();
7732                }
7733                res.add(pkg);
7734                try {
7735                    updateSharedLibrariesLPw(pkg, changingPkg);
7736                } catch (PackageManagerException e) {
7737                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7738                }
7739            }
7740        }
7741        return res;
7742    }
7743
7744    /**
7745     * Derive the value of the {@code cpuAbiOverride} based on the provided
7746     * value and an optional stored value from the package settings.
7747     */
7748    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7749        String cpuAbiOverride = null;
7750
7751        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7752            cpuAbiOverride = null;
7753        } else if (abiOverride != null) {
7754            cpuAbiOverride = abiOverride;
7755        } else if (settings != null) {
7756            cpuAbiOverride = settings.cpuAbiOverrideString;
7757        }
7758
7759        return cpuAbiOverride;
7760    }
7761
7762    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7763            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7764                    throws PackageManagerException {
7765        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7766        // If the package has children and this is the first dive in the function
7767        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7768        // whether all packages (parent and children) would be successfully scanned
7769        // before the actual scan since scanning mutates internal state and we want
7770        // to atomically install the package and its children.
7771        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7772            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7773                scanFlags |= SCAN_CHECK_ONLY;
7774            }
7775        } else {
7776            scanFlags &= ~SCAN_CHECK_ONLY;
7777        }
7778
7779        final PackageParser.Package scannedPkg;
7780        try {
7781            // Scan the parent
7782            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7783            // Scan the children
7784            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7785            for (int i = 0; i < childCount; i++) {
7786                PackageParser.Package childPkg = pkg.childPackages.get(i);
7787                scanPackageLI(childPkg, policyFlags,
7788                        scanFlags, currentTime, user);
7789            }
7790        } finally {
7791            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7792        }
7793
7794        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7795            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7796        }
7797
7798        return scannedPkg;
7799    }
7800
7801    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7802            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7803        boolean success = false;
7804        try {
7805            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7806                    currentTime, user);
7807            success = true;
7808            return res;
7809        } finally {
7810            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7811                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7812                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7813                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7814                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7815            }
7816        }
7817    }
7818
7819    /**
7820     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7821     */
7822    private static boolean apkHasCode(String fileName) {
7823        StrictJarFile jarFile = null;
7824        try {
7825            jarFile = new StrictJarFile(fileName,
7826                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7827            return jarFile.findEntry("classes.dex") != null;
7828        } catch (IOException ignore) {
7829        } finally {
7830            try {
7831                if (jarFile != null) {
7832                    jarFile.close();
7833                }
7834            } catch (IOException ignore) {}
7835        }
7836        return false;
7837    }
7838
7839    /**
7840     * Enforces code policy for the package. This ensures that if an APK has
7841     * declared hasCode="true" in its manifest that the APK actually contains
7842     * code.
7843     *
7844     * @throws PackageManagerException If bytecode could not be found when it should exist
7845     */
7846    private static void enforceCodePolicy(PackageParser.Package pkg)
7847            throws PackageManagerException {
7848        final boolean shouldHaveCode =
7849                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7850        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7851            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7852                    "Package " + pkg.baseCodePath + " code is missing");
7853        }
7854
7855        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7856            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7857                final boolean splitShouldHaveCode =
7858                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7859                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7860                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7861                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7862                }
7863            }
7864        }
7865    }
7866
7867    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7868            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7869            throws PackageManagerException {
7870        final File scanFile = new File(pkg.codePath);
7871        if (pkg.applicationInfo.getCodePath() == null ||
7872                pkg.applicationInfo.getResourcePath() == null) {
7873            // Bail out. The resource and code paths haven't been set.
7874            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7875                    "Code and resource paths haven't been set correctly");
7876        }
7877
7878        // Apply policy
7879        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7880            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7881            if (pkg.applicationInfo.isDirectBootAware()) {
7882                // we're direct boot aware; set for all components
7883                for (PackageParser.Service s : pkg.services) {
7884                    s.info.encryptionAware = s.info.directBootAware = true;
7885                }
7886                for (PackageParser.Provider p : pkg.providers) {
7887                    p.info.encryptionAware = p.info.directBootAware = true;
7888                }
7889                for (PackageParser.Activity a : pkg.activities) {
7890                    a.info.encryptionAware = a.info.directBootAware = true;
7891                }
7892                for (PackageParser.Activity r : pkg.receivers) {
7893                    r.info.encryptionAware = r.info.directBootAware = true;
7894                }
7895            }
7896        } else {
7897            // Only allow system apps to be flagged as core apps.
7898            pkg.coreApp = false;
7899            // clear flags not applicable to regular apps
7900            pkg.applicationInfo.privateFlags &=
7901                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7902            pkg.applicationInfo.privateFlags &=
7903                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7904        }
7905        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7906
7907        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7908            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7909        }
7910
7911        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7912            enforceCodePolicy(pkg);
7913        }
7914
7915        if (mCustomResolverComponentName != null &&
7916                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7917            setUpCustomResolverActivity(pkg);
7918        }
7919
7920        if (pkg.packageName.equals("android")) {
7921            synchronized (mPackages) {
7922                if (mAndroidApplication != null) {
7923                    Slog.w(TAG, "*************************************************");
7924                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7925                    Slog.w(TAG, " file=" + scanFile);
7926                    Slog.w(TAG, "*************************************************");
7927                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7928                            "Core android package being redefined.  Skipping.");
7929                }
7930
7931                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7932                    // Set up information for our fall-back user intent resolution activity.
7933                    mPlatformPackage = pkg;
7934                    pkg.mVersionCode = mSdkVersion;
7935                    mAndroidApplication = pkg.applicationInfo;
7936
7937                    if (!mResolverReplaced) {
7938                        mResolveActivity.applicationInfo = mAndroidApplication;
7939                        mResolveActivity.name = ResolverActivity.class.getName();
7940                        mResolveActivity.packageName = mAndroidApplication.packageName;
7941                        mResolveActivity.processName = "system:ui";
7942                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7943                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7944                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7945                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
7946                        mResolveActivity.exported = true;
7947                        mResolveActivity.enabled = true;
7948                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
7949                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
7950                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
7951                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
7952                                | ActivityInfo.CONFIG_ORIENTATION
7953                                | ActivityInfo.CONFIG_KEYBOARD
7954                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
7955                        mResolveInfo.activityInfo = mResolveActivity;
7956                        mResolveInfo.priority = 0;
7957                        mResolveInfo.preferredOrder = 0;
7958                        mResolveInfo.match = 0;
7959                        mResolveComponentName = new ComponentName(
7960                                mAndroidApplication.packageName, mResolveActivity.name);
7961                    }
7962                }
7963            }
7964        }
7965
7966        if (DEBUG_PACKAGE_SCANNING) {
7967            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7968                Log.d(TAG, "Scanning package " + pkg.packageName);
7969        }
7970
7971        synchronized (mPackages) {
7972            if (mPackages.containsKey(pkg.packageName)
7973                    || mSharedLibraries.containsKey(pkg.packageName)) {
7974                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7975                        "Application package " + pkg.packageName
7976                                + " already installed.  Skipping duplicate.");
7977            }
7978
7979            // If we're only installing presumed-existing packages, require that the
7980            // scanned APK is both already known and at the path previously established
7981            // for it.  Previously unknown packages we pick up normally, but if we have an
7982            // a priori expectation about this package's install presence, enforce it.
7983            // With a singular exception for new system packages. When an OTA contains
7984            // a new system package, we allow the codepath to change from a system location
7985            // to the user-installed location. If we don't allow this change, any newer,
7986            // user-installed version of the application will be ignored.
7987            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7988                if (mExpectingBetter.containsKey(pkg.packageName)) {
7989                    logCriticalInfo(Log.WARN,
7990                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7991                } else {
7992                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7993                    if (known != null) {
7994                        if (DEBUG_PACKAGE_SCANNING) {
7995                            Log.d(TAG, "Examining " + pkg.codePath
7996                                    + " and requiring known paths " + known.codePathString
7997                                    + " & " + known.resourcePathString);
7998                        }
7999                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8000                                || !pkg.applicationInfo.getResourcePath().equals(
8001                                known.resourcePathString)) {
8002                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8003                                    "Application package " + pkg.packageName
8004                                            + " found at " + pkg.applicationInfo.getCodePath()
8005                                            + " but expected at " + known.codePathString
8006                                            + "; ignoring.");
8007                        }
8008                    }
8009                }
8010            }
8011        }
8012
8013        // Initialize package source and resource directories
8014        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8015        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8016
8017        SharedUserSetting suid = null;
8018        PackageSetting pkgSetting = null;
8019
8020        if (!isSystemApp(pkg)) {
8021            // Only system apps can use these features.
8022            pkg.mOriginalPackages = null;
8023            pkg.mRealPackage = null;
8024            pkg.mAdoptPermissions = null;
8025        }
8026
8027        // Getting the package setting may have a side-effect, so if we
8028        // are only checking if scan would succeed, stash a copy of the
8029        // old setting to restore at the end.
8030        PackageSetting nonMutatedPs = null;
8031
8032        // writer
8033        synchronized (mPackages) {
8034            if (pkg.mSharedUserId != null) {
8035                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8036                if (suid == null) {
8037                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8038                            "Creating application package " + pkg.packageName
8039                            + " for shared user failed");
8040                }
8041                if (DEBUG_PACKAGE_SCANNING) {
8042                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8043                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8044                                + "): packages=" + suid.packages);
8045                }
8046            }
8047
8048            // Check if we are renaming from an original package name.
8049            PackageSetting origPackage = null;
8050            String realName = null;
8051            if (pkg.mOriginalPackages != null) {
8052                // This package may need to be renamed to a previously
8053                // installed name.  Let's check on that...
8054                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8055                if (pkg.mOriginalPackages.contains(renamed)) {
8056                    // This package had originally been installed as the
8057                    // original name, and we have already taken care of
8058                    // transitioning to the new one.  Just update the new
8059                    // one to continue using the old name.
8060                    realName = pkg.mRealPackage;
8061                    if (!pkg.packageName.equals(renamed)) {
8062                        // Callers into this function may have already taken
8063                        // care of renaming the package; only do it here if
8064                        // it is not already done.
8065                        pkg.setPackageName(renamed);
8066                    }
8067
8068                } else {
8069                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8070                        if ((origPackage = mSettings.peekPackageLPr(
8071                                pkg.mOriginalPackages.get(i))) != null) {
8072                            // We do have the package already installed under its
8073                            // original name...  should we use it?
8074                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8075                                // New package is not compatible with original.
8076                                origPackage = null;
8077                                continue;
8078                            } else if (origPackage.sharedUser != null) {
8079                                // Make sure uid is compatible between packages.
8080                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8081                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8082                                            + " to " + pkg.packageName + ": old uid "
8083                                            + origPackage.sharedUser.name
8084                                            + " differs from " + pkg.mSharedUserId);
8085                                    origPackage = null;
8086                                    continue;
8087                                }
8088                                // TODO: Add case when shared user id is added [b/28144775]
8089                            } else {
8090                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8091                                        + pkg.packageName + " to old name " + origPackage.name);
8092                            }
8093                            break;
8094                        }
8095                    }
8096                }
8097            }
8098
8099            if (mTransferedPackages.contains(pkg.packageName)) {
8100                Slog.w(TAG, "Package " + pkg.packageName
8101                        + " was transferred to another, but its .apk remains");
8102            }
8103
8104            // See comments in nonMutatedPs declaration
8105            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8106                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8107                if (foundPs != null) {
8108                    nonMutatedPs = new PackageSetting(foundPs);
8109                }
8110            }
8111
8112            // Just create the setting, don't add it yet. For already existing packages
8113            // the PkgSetting exists already and doesn't have to be created.
8114            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8115                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8116                    pkg.applicationInfo.primaryCpuAbi,
8117                    pkg.applicationInfo.secondaryCpuAbi,
8118                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8119                    user, false);
8120            if (pkgSetting == null) {
8121                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8122                        "Creating application package " + pkg.packageName + " failed");
8123            }
8124
8125            if (pkgSetting.origPackage != null) {
8126                // If we are first transitioning from an original package,
8127                // fix up the new package's name now.  We need to do this after
8128                // looking up the package under its new name, so getPackageLP
8129                // can take care of fiddling things correctly.
8130                pkg.setPackageName(origPackage.name);
8131
8132                // File a report about this.
8133                String msg = "New package " + pkgSetting.realName
8134                        + " renamed to replace old package " + pkgSetting.name;
8135                reportSettingsProblem(Log.WARN, msg);
8136
8137                // Make a note of it.
8138                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8139                    mTransferedPackages.add(origPackage.name);
8140                }
8141
8142                // No longer need to retain this.
8143                pkgSetting.origPackage = null;
8144            }
8145
8146            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8147                // Make a note of it.
8148                mTransferedPackages.add(pkg.packageName);
8149            }
8150
8151            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8152                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8153            }
8154
8155            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8156                // Check all shared libraries and map to their actual file path.
8157                // We only do this here for apps not on a system dir, because those
8158                // are the only ones that can fail an install due to this.  We
8159                // will take care of the system apps by updating all of their
8160                // library paths after the scan is done.
8161                updateSharedLibrariesLPw(pkg, null);
8162            }
8163
8164            if (mFoundPolicyFile) {
8165                SELinuxMMAC.assignSeinfoValue(pkg);
8166            }
8167
8168            pkg.applicationInfo.uid = pkgSetting.appId;
8169            pkg.mExtras = pkgSetting;
8170            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8171                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8172                    // We just determined the app is signed correctly, so bring
8173                    // over the latest parsed certs.
8174                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8175                } else {
8176                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8177                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8178                                "Package " + pkg.packageName + " upgrade keys do not match the "
8179                                + "previously installed version");
8180                    } else {
8181                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8182                        String msg = "System package " + pkg.packageName
8183                            + " signature changed; retaining data.";
8184                        reportSettingsProblem(Log.WARN, msg);
8185                    }
8186                }
8187            } else {
8188                try {
8189                    verifySignaturesLP(pkgSetting, pkg);
8190                    // We just determined the app is signed correctly, so bring
8191                    // over the latest parsed certs.
8192                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8193                } catch (PackageManagerException e) {
8194                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8195                        throw e;
8196                    }
8197                    // The signature has changed, but this package is in the system
8198                    // image...  let's recover!
8199                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8200                    // However...  if this package is part of a shared user, but it
8201                    // doesn't match the signature of the shared user, let's fail.
8202                    // What this means is that you can't change the signatures
8203                    // associated with an overall shared user, which doesn't seem all
8204                    // that unreasonable.
8205                    if (pkgSetting.sharedUser != null) {
8206                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8207                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8208                            throw new PackageManagerException(
8209                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8210                                            "Signature mismatch for shared user: "
8211                                            + pkgSetting.sharedUser);
8212                        }
8213                    }
8214                    // File a report about this.
8215                    String msg = "System package " + pkg.packageName
8216                        + " signature changed; retaining data.";
8217                    reportSettingsProblem(Log.WARN, msg);
8218                }
8219            }
8220            // Verify that this new package doesn't have any content providers
8221            // that conflict with existing packages.  Only do this if the
8222            // package isn't already installed, since we don't want to break
8223            // things that are installed.
8224            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8225                final int N = pkg.providers.size();
8226                int i;
8227                for (i=0; i<N; i++) {
8228                    PackageParser.Provider p = pkg.providers.get(i);
8229                    if (p.info.authority != null) {
8230                        String names[] = p.info.authority.split(";");
8231                        for (int j = 0; j < names.length; j++) {
8232                            if (mProvidersByAuthority.containsKey(names[j])) {
8233                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8234                                final String otherPackageName =
8235                                        ((other != null && other.getComponentName() != null) ?
8236                                                other.getComponentName().getPackageName() : "?");
8237                                throw new PackageManagerException(
8238                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8239                                                "Can't install because provider name " + names[j]
8240                                                + " (in package " + pkg.applicationInfo.packageName
8241                                                + ") is already used by " + otherPackageName);
8242                            }
8243                        }
8244                    }
8245                }
8246            }
8247
8248            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8249                // This package wants to adopt ownership of permissions from
8250                // another package.
8251                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8252                    final String origName = pkg.mAdoptPermissions.get(i);
8253                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8254                    if (orig != null) {
8255                        if (verifyPackageUpdateLPr(orig, pkg)) {
8256                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8257                                    + pkg.packageName);
8258                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8259                        }
8260                    }
8261                }
8262            }
8263        }
8264
8265        final String pkgName = pkg.packageName;
8266
8267        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8268        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8269        pkg.applicationInfo.processName = fixProcessName(
8270                pkg.applicationInfo.packageName,
8271                pkg.applicationInfo.processName,
8272                pkg.applicationInfo.uid);
8273
8274        if (pkg != mPlatformPackage) {
8275            // Get all of our default paths setup
8276            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8277        }
8278
8279        final String path = scanFile.getPath();
8280        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8281
8282        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8283            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8284
8285            // Some system apps still use directory structure for native libraries
8286            // in which case we might end up not detecting abi solely based on apk
8287            // structure. Try to detect abi based on directory structure.
8288            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8289                    pkg.applicationInfo.primaryCpuAbi == null) {
8290                setBundledAppAbisAndRoots(pkg, pkgSetting);
8291                setNativeLibraryPaths(pkg);
8292            }
8293
8294        } else {
8295            if ((scanFlags & SCAN_MOVE) != 0) {
8296                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8297                // but we already have this packages package info in the PackageSetting. We just
8298                // use that and derive the native library path based on the new codepath.
8299                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8300                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8301            }
8302
8303            // Set native library paths again. For moves, the path will be updated based on the
8304            // ABIs we've determined above. For non-moves, the path will be updated based on the
8305            // ABIs we determined during compilation, but the path will depend on the final
8306            // package path (after the rename away from the stage path).
8307            setNativeLibraryPaths(pkg);
8308        }
8309
8310        // This is a special case for the "system" package, where the ABI is
8311        // dictated by the zygote configuration (and init.rc). We should keep track
8312        // of this ABI so that we can deal with "normal" applications that run under
8313        // the same UID correctly.
8314        if (mPlatformPackage == pkg) {
8315            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8316                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8317        }
8318
8319        // If there's a mismatch between the abi-override in the package setting
8320        // and the abiOverride specified for the install. Warn about this because we
8321        // would've already compiled the app without taking the package setting into
8322        // account.
8323        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8324            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8325                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8326                        " for package " + pkg.packageName);
8327            }
8328        }
8329
8330        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8331        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8332        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8333
8334        // Copy the derived override back to the parsed package, so that we can
8335        // update the package settings accordingly.
8336        pkg.cpuAbiOverride = cpuAbiOverride;
8337
8338        if (DEBUG_ABI_SELECTION) {
8339            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8340                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8341                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8342        }
8343
8344        // Push the derived path down into PackageSettings so we know what to
8345        // clean up at uninstall time.
8346        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8347
8348        if (DEBUG_ABI_SELECTION) {
8349            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8350                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8351                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8352        }
8353
8354        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8355            // We don't do this here during boot because we can do it all
8356            // at once after scanning all existing packages.
8357            //
8358            // We also do this *before* we perform dexopt on this package, so that
8359            // we can avoid redundant dexopts, and also to make sure we've got the
8360            // code and package path correct.
8361            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8362                    pkg, true /* boot complete */);
8363        }
8364
8365        if (mFactoryTest && pkg.requestedPermissions.contains(
8366                android.Manifest.permission.FACTORY_TEST)) {
8367            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8368        }
8369
8370        ArrayList<PackageParser.Package> clientLibPkgs = null;
8371
8372        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8373            if (nonMutatedPs != null) {
8374                synchronized (mPackages) {
8375                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8376                }
8377            }
8378            return pkg;
8379        }
8380
8381        // Only privileged apps and updated privileged apps can add child packages.
8382        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8383            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8384                throw new PackageManagerException("Only privileged apps and updated "
8385                        + "privileged apps can add child packages. Ignoring package "
8386                        + pkg.packageName);
8387            }
8388            final int childCount = pkg.childPackages.size();
8389            for (int i = 0; i < childCount; i++) {
8390                PackageParser.Package childPkg = pkg.childPackages.get(i);
8391                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8392                        childPkg.packageName)) {
8393                    throw new PackageManagerException("Cannot override a child package of "
8394                            + "another disabled system app. Ignoring package " + pkg.packageName);
8395                }
8396            }
8397        }
8398
8399        // writer
8400        synchronized (mPackages) {
8401            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8402                // Only system apps can add new shared libraries.
8403                if (pkg.libraryNames != null) {
8404                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8405                        String name = pkg.libraryNames.get(i);
8406                        boolean allowed = false;
8407                        if (pkg.isUpdatedSystemApp()) {
8408                            // New library entries can only be added through the
8409                            // system image.  This is important to get rid of a lot
8410                            // of nasty edge cases: for example if we allowed a non-
8411                            // system update of the app to add a library, then uninstalling
8412                            // the update would make the library go away, and assumptions
8413                            // we made such as through app install filtering would now
8414                            // have allowed apps on the device which aren't compatible
8415                            // with it.  Better to just have the restriction here, be
8416                            // conservative, and create many fewer cases that can negatively
8417                            // impact the user experience.
8418                            final PackageSetting sysPs = mSettings
8419                                    .getDisabledSystemPkgLPr(pkg.packageName);
8420                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8421                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8422                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8423                                        allowed = true;
8424                                        break;
8425                                    }
8426                                }
8427                            }
8428                        } else {
8429                            allowed = true;
8430                        }
8431                        if (allowed) {
8432                            if (!mSharedLibraries.containsKey(name)) {
8433                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8434                            } else if (!name.equals(pkg.packageName)) {
8435                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8436                                        + name + " already exists; skipping");
8437                            }
8438                        } else {
8439                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8440                                    + name + " that is not declared on system image; skipping");
8441                        }
8442                    }
8443                    if ((scanFlags & SCAN_BOOTING) == 0) {
8444                        // If we are not booting, we need to update any applications
8445                        // that are clients of our shared library.  If we are booting,
8446                        // this will all be done once the scan is complete.
8447                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8448                    }
8449                }
8450            }
8451        }
8452
8453        if ((scanFlags & SCAN_BOOTING) != 0) {
8454            // No apps can run during boot scan, so they don't need to be frozen
8455        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8456            // Caller asked to not kill app, so it's probably not frozen
8457        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8458            // Caller asked us to ignore frozen check for some reason; they
8459            // probably didn't know the package name
8460        } else {
8461            // We're doing major surgery on this package, so it better be frozen
8462            // right now to keep it from launching
8463            checkPackageFrozen(pkgName);
8464        }
8465
8466        // Also need to kill any apps that are dependent on the library.
8467        if (clientLibPkgs != null) {
8468            for (int i=0; i<clientLibPkgs.size(); i++) {
8469                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8470                killApplication(clientPkg.applicationInfo.packageName,
8471                        clientPkg.applicationInfo.uid, "update lib");
8472            }
8473        }
8474
8475        // Make sure we're not adding any bogus keyset info
8476        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8477        ksms.assertScannedPackageValid(pkg);
8478
8479        // writer
8480        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8481
8482        boolean createIdmapFailed = false;
8483        synchronized (mPackages) {
8484            // We don't expect installation to fail beyond this point
8485
8486            if (pkgSetting.pkg != null) {
8487                // Note that |user| might be null during the initial boot scan. If a codePath
8488                // for an app has changed during a boot scan, it's due to an app update that's
8489                // part of the system partition and marker changes must be applied to all users.
8490                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8491                    (user != null) ? user : UserHandle.ALL);
8492            }
8493
8494            // Add the new setting to mSettings
8495            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8496            // Add the new setting to mPackages
8497            mPackages.put(pkg.applicationInfo.packageName, pkg);
8498            // Make sure we don't accidentally delete its data.
8499            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8500            while (iter.hasNext()) {
8501                PackageCleanItem item = iter.next();
8502                if (pkgName.equals(item.packageName)) {
8503                    iter.remove();
8504                }
8505            }
8506
8507            // Take care of first install / last update times.
8508            if (currentTime != 0) {
8509                if (pkgSetting.firstInstallTime == 0) {
8510                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8511                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8512                    pkgSetting.lastUpdateTime = currentTime;
8513                }
8514            } else if (pkgSetting.firstInstallTime == 0) {
8515                // We need *something*.  Take time time stamp of the file.
8516                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8517            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8518                if (scanFileTime != pkgSetting.timeStamp) {
8519                    // A package on the system image has changed; consider this
8520                    // to be an update.
8521                    pkgSetting.lastUpdateTime = scanFileTime;
8522                }
8523            }
8524
8525            // Add the package's KeySets to the global KeySetManagerService
8526            ksms.addScannedPackageLPw(pkg);
8527
8528            int N = pkg.providers.size();
8529            StringBuilder r = null;
8530            int i;
8531            for (i=0; i<N; i++) {
8532                PackageParser.Provider p = pkg.providers.get(i);
8533                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8534                        p.info.processName, pkg.applicationInfo.uid);
8535                mProviders.addProvider(p);
8536                p.syncable = p.info.isSyncable;
8537                if (p.info.authority != null) {
8538                    String names[] = p.info.authority.split(";");
8539                    p.info.authority = null;
8540                    for (int j = 0; j < names.length; j++) {
8541                        if (j == 1 && p.syncable) {
8542                            // We only want the first authority for a provider to possibly be
8543                            // syncable, so if we already added this provider using a different
8544                            // authority clear the syncable flag. We copy the provider before
8545                            // changing it because the mProviders object contains a reference
8546                            // to a provider that we don't want to change.
8547                            // Only do this for the second authority since the resulting provider
8548                            // object can be the same for all future authorities for this provider.
8549                            p = new PackageParser.Provider(p);
8550                            p.syncable = false;
8551                        }
8552                        if (!mProvidersByAuthority.containsKey(names[j])) {
8553                            mProvidersByAuthority.put(names[j], p);
8554                            if (p.info.authority == null) {
8555                                p.info.authority = names[j];
8556                            } else {
8557                                p.info.authority = p.info.authority + ";" + names[j];
8558                            }
8559                            if (DEBUG_PACKAGE_SCANNING) {
8560                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8561                                    Log.d(TAG, "Registered content provider: " + names[j]
8562                                            + ", className = " + p.info.name + ", isSyncable = "
8563                                            + p.info.isSyncable);
8564                            }
8565                        } else {
8566                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8567                            Slog.w(TAG, "Skipping provider name " + names[j] +
8568                                    " (in package " + pkg.applicationInfo.packageName +
8569                                    "): name already used by "
8570                                    + ((other != null && other.getComponentName() != null)
8571                                            ? other.getComponentName().getPackageName() : "?"));
8572                        }
8573                    }
8574                }
8575                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8576                    if (r == null) {
8577                        r = new StringBuilder(256);
8578                    } else {
8579                        r.append(' ');
8580                    }
8581                    r.append(p.info.name);
8582                }
8583            }
8584            if (r != null) {
8585                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8586            }
8587
8588            N = pkg.services.size();
8589            r = null;
8590            for (i=0; i<N; i++) {
8591                PackageParser.Service s = pkg.services.get(i);
8592                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8593                        s.info.processName, pkg.applicationInfo.uid);
8594                mServices.addService(s);
8595                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8596                    if (r == null) {
8597                        r = new StringBuilder(256);
8598                    } else {
8599                        r.append(' ');
8600                    }
8601                    r.append(s.info.name);
8602                }
8603            }
8604            if (r != null) {
8605                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8606            }
8607
8608            N = pkg.receivers.size();
8609            r = null;
8610            for (i=0; i<N; i++) {
8611                PackageParser.Activity a = pkg.receivers.get(i);
8612                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8613                        a.info.processName, pkg.applicationInfo.uid);
8614                mReceivers.addActivity(a, "receiver");
8615                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8616                    if (r == null) {
8617                        r = new StringBuilder(256);
8618                    } else {
8619                        r.append(' ');
8620                    }
8621                    r.append(a.info.name);
8622                }
8623            }
8624            if (r != null) {
8625                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8626            }
8627
8628            N = pkg.activities.size();
8629            r = null;
8630            for (i=0; i<N; i++) {
8631                PackageParser.Activity a = pkg.activities.get(i);
8632                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8633                        a.info.processName, pkg.applicationInfo.uid);
8634                mActivities.addActivity(a, "activity");
8635                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8636                    if (r == null) {
8637                        r = new StringBuilder(256);
8638                    } else {
8639                        r.append(' ');
8640                    }
8641                    r.append(a.info.name);
8642                }
8643            }
8644            if (r != null) {
8645                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8646            }
8647
8648            N = pkg.permissionGroups.size();
8649            r = null;
8650            for (i=0; i<N; i++) {
8651                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8652                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8653                final String curPackageName = cur == null ? null : cur.info.packageName;
8654                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
8655                if (cur == null || isPackageUpdate) {
8656                    mPermissionGroups.put(pg.info.name, pg);
8657                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8658                        if (r == null) {
8659                            r = new StringBuilder(256);
8660                        } else {
8661                            r.append(' ');
8662                        }
8663                        if (isPackageUpdate) {
8664                            r.append("UPD:");
8665                        }
8666                        r.append(pg.info.name);
8667                    }
8668                } else {
8669                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8670                            + pg.info.packageName + " ignored: original from "
8671                            + cur.info.packageName);
8672                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8673                        if (r == null) {
8674                            r = new StringBuilder(256);
8675                        } else {
8676                            r.append(' ');
8677                        }
8678                        r.append("DUP:");
8679                        r.append(pg.info.name);
8680                    }
8681                }
8682            }
8683            if (r != null) {
8684                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8685            }
8686
8687            N = pkg.permissions.size();
8688            r = null;
8689            for (i=0; i<N; i++) {
8690                PackageParser.Permission p = pkg.permissions.get(i);
8691
8692                // Assume by default that we did not install this permission into the system.
8693                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8694
8695                // Now that permission groups have a special meaning, we ignore permission
8696                // groups for legacy apps to prevent unexpected behavior. In particular,
8697                // permissions for one app being granted to someone just becase they happen
8698                // to be in a group defined by another app (before this had no implications).
8699                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8700                    p.group = mPermissionGroups.get(p.info.group);
8701                    // Warn for a permission in an unknown group.
8702                    if (p.info.group != null && p.group == null) {
8703                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8704                                + p.info.packageName + " in an unknown group " + p.info.group);
8705                    }
8706                }
8707
8708                ArrayMap<String, BasePermission> permissionMap =
8709                        p.tree ? mSettings.mPermissionTrees
8710                                : mSettings.mPermissions;
8711                BasePermission bp = permissionMap.get(p.info.name);
8712
8713                // Allow system apps to redefine non-system permissions
8714                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8715                    final boolean currentOwnerIsSystem = (bp.perm != null
8716                            && isSystemApp(bp.perm.owner));
8717                    if (isSystemApp(p.owner)) {
8718                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8719                            // It's a built-in permission and no owner, take ownership now
8720                            bp.packageSetting = pkgSetting;
8721                            bp.perm = p;
8722                            bp.uid = pkg.applicationInfo.uid;
8723                            bp.sourcePackage = p.info.packageName;
8724                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8725                        } else if (!currentOwnerIsSystem) {
8726                            String msg = "New decl " + p.owner + " of permission  "
8727                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8728                            reportSettingsProblem(Log.WARN, msg);
8729                            bp = null;
8730                        }
8731                    }
8732                }
8733
8734                if (bp == null) {
8735                    bp = new BasePermission(p.info.name, p.info.packageName,
8736                            BasePermission.TYPE_NORMAL);
8737                    permissionMap.put(p.info.name, bp);
8738                }
8739
8740                if (bp.perm == null) {
8741                    if (bp.sourcePackage == null
8742                            || bp.sourcePackage.equals(p.info.packageName)) {
8743                        BasePermission tree = findPermissionTreeLP(p.info.name);
8744                        if (tree == null
8745                                || tree.sourcePackage.equals(p.info.packageName)) {
8746                            bp.packageSetting = pkgSetting;
8747                            bp.perm = p;
8748                            bp.uid = pkg.applicationInfo.uid;
8749                            bp.sourcePackage = p.info.packageName;
8750                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8751                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8752                                if (r == null) {
8753                                    r = new StringBuilder(256);
8754                                } else {
8755                                    r.append(' ');
8756                                }
8757                                r.append(p.info.name);
8758                            }
8759                        } else {
8760                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8761                                    + p.info.packageName + " ignored: base tree "
8762                                    + tree.name + " is from package "
8763                                    + tree.sourcePackage);
8764                        }
8765                    } else {
8766                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8767                                + p.info.packageName + " ignored: original from "
8768                                + bp.sourcePackage);
8769                    }
8770                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8771                    if (r == null) {
8772                        r = new StringBuilder(256);
8773                    } else {
8774                        r.append(' ');
8775                    }
8776                    r.append("DUP:");
8777                    r.append(p.info.name);
8778                }
8779                if (bp.perm == p) {
8780                    bp.protectionLevel = p.info.protectionLevel;
8781                }
8782            }
8783
8784            if (r != null) {
8785                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8786            }
8787
8788            N = pkg.instrumentation.size();
8789            r = null;
8790            for (i=0; i<N; i++) {
8791                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8792                a.info.packageName = pkg.applicationInfo.packageName;
8793                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8794                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8795                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8796                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8797                a.info.dataDir = pkg.applicationInfo.dataDir;
8798                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8799                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8800
8801                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8802                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8803                mInstrumentation.put(a.getComponentName(), a);
8804                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8805                    if (r == null) {
8806                        r = new StringBuilder(256);
8807                    } else {
8808                        r.append(' ');
8809                    }
8810                    r.append(a.info.name);
8811                }
8812            }
8813            if (r != null) {
8814                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8815            }
8816
8817            if (pkg.protectedBroadcasts != null) {
8818                N = pkg.protectedBroadcasts.size();
8819                for (i=0; i<N; i++) {
8820                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8821                }
8822            }
8823
8824            pkgSetting.setTimeStamp(scanFileTime);
8825
8826            // Create idmap files for pairs of (packages, overlay packages).
8827            // Note: "android", ie framework-res.apk, is handled by native layers.
8828            if (pkg.mOverlayTarget != null) {
8829                // This is an overlay package.
8830                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8831                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8832                        mOverlays.put(pkg.mOverlayTarget,
8833                                new ArrayMap<String, PackageParser.Package>());
8834                    }
8835                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8836                    map.put(pkg.packageName, pkg);
8837                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8838                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8839                        createIdmapFailed = true;
8840                    }
8841                }
8842            } else if (mOverlays.containsKey(pkg.packageName) &&
8843                    !pkg.packageName.equals("android")) {
8844                // This is a regular package, with one or more known overlay packages.
8845                createIdmapsForPackageLI(pkg);
8846            }
8847        }
8848
8849        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8850
8851        if (createIdmapFailed) {
8852            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8853                    "scanPackageLI failed to createIdmap");
8854        }
8855        return pkg;
8856    }
8857
8858    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
8859            PackageParser.Package update, UserHandle user) {
8860        if (existing.applicationInfo == null || update.applicationInfo == null) {
8861            // This isn't due to an app installation.
8862            return;
8863        }
8864
8865        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
8866        final File newCodePath = new File(update.applicationInfo.getCodePath());
8867
8868        // The codePath hasn't changed, so there's nothing for us to do.
8869        if (Objects.equals(oldCodePath, newCodePath)) {
8870            return;
8871        }
8872
8873        File canonicalNewCodePath;
8874        try {
8875            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
8876        } catch (IOException e) {
8877            Slog.w(TAG, "Failed to get canonical path.", e);
8878            return;
8879        }
8880
8881        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
8882        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
8883        // that the last component of the path (i.e, the name) doesn't need canonicalization
8884        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
8885        // but may change in the future. Hopefully this function won't exist at that point.
8886        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
8887                oldCodePath.getName());
8888
8889        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
8890        // with "@".
8891        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
8892        if (!oldMarkerPrefix.endsWith("@")) {
8893            oldMarkerPrefix += "@";
8894        }
8895        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
8896        if (!newMarkerPrefix.endsWith("@")) {
8897            newMarkerPrefix += "@";
8898        }
8899
8900        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
8901        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
8902        for (String updatedPath : updatedPaths) {
8903            String updatedPathName = new File(updatedPath).getName();
8904            markerSuffixes.add(updatedPathName.replace('/', '@'));
8905        }
8906
8907        for (int userId : resolveUserIds(user.getIdentifier())) {
8908            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
8909
8910            for (String markerSuffix : markerSuffixes) {
8911                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
8912                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
8913                if (oldForeignUseMark.exists()) {
8914                    try {
8915                        Os.rename(oldForeignUseMark.getAbsolutePath(),
8916                                newForeignUseMark.getAbsolutePath());
8917                    } catch (ErrnoException e) {
8918                        Slog.w(TAG, "Failed to rename foreign use marker", e);
8919                        oldForeignUseMark.delete();
8920                    }
8921                }
8922            }
8923        }
8924    }
8925
8926    /**
8927     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8928     * is derived purely on the basis of the contents of {@code scanFile} and
8929     * {@code cpuAbiOverride}.
8930     *
8931     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8932     */
8933    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8934                                 String cpuAbiOverride, boolean extractLibs)
8935            throws PackageManagerException {
8936        // TODO: We can probably be smarter about this stuff. For installed apps,
8937        // we can calculate this information at install time once and for all. For
8938        // system apps, we can probably assume that this information doesn't change
8939        // after the first boot scan. As things stand, we do lots of unnecessary work.
8940
8941        // Give ourselves some initial paths; we'll come back for another
8942        // pass once we've determined ABI below.
8943        setNativeLibraryPaths(pkg);
8944
8945        // We would never need to extract libs for forward-locked and external packages,
8946        // since the container service will do it for us. We shouldn't attempt to
8947        // extract libs from system app when it was not updated.
8948        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8949                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8950            extractLibs = false;
8951        }
8952
8953        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8954        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8955
8956        NativeLibraryHelper.Handle handle = null;
8957        try {
8958            handle = NativeLibraryHelper.Handle.create(pkg);
8959            // TODO(multiArch): This can be null for apps that didn't go through the
8960            // usual installation process. We can calculate it again, like we
8961            // do during install time.
8962            //
8963            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8964            // unnecessary.
8965            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8966
8967            // Null out the abis so that they can be recalculated.
8968            pkg.applicationInfo.primaryCpuAbi = null;
8969            pkg.applicationInfo.secondaryCpuAbi = null;
8970            if (isMultiArch(pkg.applicationInfo)) {
8971                // Warn if we've set an abiOverride for multi-lib packages..
8972                // By definition, we need to copy both 32 and 64 bit libraries for
8973                // such packages.
8974                if (pkg.cpuAbiOverride != null
8975                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8976                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8977                }
8978
8979                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8980                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8981                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8982                    if (extractLibs) {
8983                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8984                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8985                                useIsaSpecificSubdirs);
8986                    } else {
8987                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8988                    }
8989                }
8990
8991                maybeThrowExceptionForMultiArchCopy(
8992                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8993
8994                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8995                    if (extractLibs) {
8996                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8997                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8998                                useIsaSpecificSubdirs);
8999                    } else {
9000                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9001                    }
9002                }
9003
9004                maybeThrowExceptionForMultiArchCopy(
9005                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9006
9007                if (abi64 >= 0) {
9008                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9009                }
9010
9011                if (abi32 >= 0) {
9012                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9013                    if (abi64 >= 0) {
9014                        if (pkg.use32bitAbi) {
9015                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9016                            pkg.applicationInfo.primaryCpuAbi = abi;
9017                        } else {
9018                            pkg.applicationInfo.secondaryCpuAbi = abi;
9019                        }
9020                    } else {
9021                        pkg.applicationInfo.primaryCpuAbi = abi;
9022                    }
9023                }
9024
9025            } else {
9026                String[] abiList = (cpuAbiOverride != null) ?
9027                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9028
9029                // Enable gross and lame hacks for apps that are built with old
9030                // SDK tools. We must scan their APKs for renderscript bitcode and
9031                // not launch them if it's present. Don't bother checking on devices
9032                // that don't have 64 bit support.
9033                boolean needsRenderScriptOverride = false;
9034                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9035                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9036                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9037                    needsRenderScriptOverride = true;
9038                }
9039
9040                final int copyRet;
9041                if (extractLibs) {
9042                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9043                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9044                } else {
9045                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9046                }
9047
9048                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9049                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9050                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9051                }
9052
9053                if (copyRet >= 0) {
9054                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9055                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9056                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9057                } else if (needsRenderScriptOverride) {
9058                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9059                }
9060            }
9061        } catch (IOException ioe) {
9062            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9063        } finally {
9064            IoUtils.closeQuietly(handle);
9065        }
9066
9067        // Now that we've calculated the ABIs and determined if it's an internal app,
9068        // we will go ahead and populate the nativeLibraryPath.
9069        setNativeLibraryPaths(pkg);
9070    }
9071
9072    /**
9073     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9074     * i.e, so that all packages can be run inside a single process if required.
9075     *
9076     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9077     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9078     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9079     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9080     * updating a package that belongs to a shared user.
9081     *
9082     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9083     * adds unnecessary complexity.
9084     */
9085    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9086            PackageParser.Package scannedPackage, boolean bootComplete) {
9087        String requiredInstructionSet = null;
9088        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9089            requiredInstructionSet = VMRuntime.getInstructionSet(
9090                     scannedPackage.applicationInfo.primaryCpuAbi);
9091        }
9092
9093        PackageSetting requirer = null;
9094        for (PackageSetting ps : packagesForUser) {
9095            // If packagesForUser contains scannedPackage, we skip it. This will happen
9096            // when scannedPackage is an update of an existing package. Without this check,
9097            // we will never be able to change the ABI of any package belonging to a shared
9098            // user, even if it's compatible with other packages.
9099            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9100                if (ps.primaryCpuAbiString == null) {
9101                    continue;
9102                }
9103
9104                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9105                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9106                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9107                    // this but there's not much we can do.
9108                    String errorMessage = "Instruction set mismatch, "
9109                            + ((requirer == null) ? "[caller]" : requirer)
9110                            + " requires " + requiredInstructionSet + " whereas " + ps
9111                            + " requires " + instructionSet;
9112                    Slog.w(TAG, errorMessage);
9113                }
9114
9115                if (requiredInstructionSet == null) {
9116                    requiredInstructionSet = instructionSet;
9117                    requirer = ps;
9118                }
9119            }
9120        }
9121
9122        if (requiredInstructionSet != null) {
9123            String adjustedAbi;
9124            if (requirer != null) {
9125                // requirer != null implies that either scannedPackage was null or that scannedPackage
9126                // did not require an ABI, in which case we have to adjust scannedPackage to match
9127                // the ABI of the set (which is the same as requirer's ABI)
9128                adjustedAbi = requirer.primaryCpuAbiString;
9129                if (scannedPackage != null) {
9130                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9131                }
9132            } else {
9133                // requirer == null implies that we're updating all ABIs in the set to
9134                // match scannedPackage.
9135                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9136            }
9137
9138            for (PackageSetting ps : packagesForUser) {
9139                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9140                    if (ps.primaryCpuAbiString != null) {
9141                        continue;
9142                    }
9143
9144                    ps.primaryCpuAbiString = adjustedAbi;
9145                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9146                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9147                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9148                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9149                                + " (requirer="
9150                                + (requirer == null ? "null" : requirer.pkg.packageName)
9151                                + ", scannedPackage="
9152                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9153                                + ")");
9154                        try {
9155                            mInstaller.rmdex(ps.codePathString,
9156                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9157                        } catch (InstallerException ignored) {
9158                        }
9159                    }
9160                }
9161            }
9162        }
9163    }
9164
9165    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9166        synchronized (mPackages) {
9167            mResolverReplaced = true;
9168            // Set up information for custom user intent resolution activity.
9169            mResolveActivity.applicationInfo = pkg.applicationInfo;
9170            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9171            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9172            mResolveActivity.processName = pkg.applicationInfo.packageName;
9173            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9174            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9175                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9176            mResolveActivity.theme = 0;
9177            mResolveActivity.exported = true;
9178            mResolveActivity.enabled = true;
9179            mResolveInfo.activityInfo = mResolveActivity;
9180            mResolveInfo.priority = 0;
9181            mResolveInfo.preferredOrder = 0;
9182            mResolveInfo.match = 0;
9183            mResolveComponentName = mCustomResolverComponentName;
9184            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9185                    mResolveComponentName);
9186        }
9187    }
9188
9189    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9190        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9191
9192        // Set up information for ephemeral installer activity
9193        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9194        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9195        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9196        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9197        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9198        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9199                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9200        mEphemeralInstallerActivity.theme = 0;
9201        mEphemeralInstallerActivity.exported = true;
9202        mEphemeralInstallerActivity.enabled = true;
9203        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9204        mEphemeralInstallerInfo.priority = 0;
9205        mEphemeralInstallerInfo.preferredOrder = 0;
9206        mEphemeralInstallerInfo.match = 0;
9207
9208        if (DEBUG_EPHEMERAL) {
9209            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9210        }
9211    }
9212
9213    private static String calculateBundledApkRoot(final String codePathString) {
9214        final File codePath = new File(codePathString);
9215        final File codeRoot;
9216        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9217            codeRoot = Environment.getRootDirectory();
9218        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9219            codeRoot = Environment.getOemDirectory();
9220        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9221            codeRoot = Environment.getVendorDirectory();
9222        } else {
9223            // Unrecognized code path; take its top real segment as the apk root:
9224            // e.g. /something/app/blah.apk => /something
9225            try {
9226                File f = codePath.getCanonicalFile();
9227                File parent = f.getParentFile();    // non-null because codePath is a file
9228                File tmp;
9229                while ((tmp = parent.getParentFile()) != null) {
9230                    f = parent;
9231                    parent = tmp;
9232                }
9233                codeRoot = f;
9234                Slog.w(TAG, "Unrecognized code path "
9235                        + codePath + " - using " + codeRoot);
9236            } catch (IOException e) {
9237                // Can't canonicalize the code path -- shenanigans?
9238                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9239                return Environment.getRootDirectory().getPath();
9240            }
9241        }
9242        return codeRoot.getPath();
9243    }
9244
9245    /**
9246     * Derive and set the location of native libraries for the given package,
9247     * which varies depending on where and how the package was installed.
9248     */
9249    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9250        final ApplicationInfo info = pkg.applicationInfo;
9251        final String codePath = pkg.codePath;
9252        final File codeFile = new File(codePath);
9253        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9254        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9255
9256        info.nativeLibraryRootDir = null;
9257        info.nativeLibraryRootRequiresIsa = false;
9258        info.nativeLibraryDir = null;
9259        info.secondaryNativeLibraryDir = null;
9260
9261        if (isApkFile(codeFile)) {
9262            // Monolithic install
9263            if (bundledApp) {
9264                // If "/system/lib64/apkname" exists, assume that is the per-package
9265                // native library directory to use; otherwise use "/system/lib/apkname".
9266                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9267                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9268                        getPrimaryInstructionSet(info));
9269
9270                // This is a bundled system app so choose the path based on the ABI.
9271                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9272                // is just the default path.
9273                final String apkName = deriveCodePathName(codePath);
9274                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9275                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9276                        apkName).getAbsolutePath();
9277
9278                if (info.secondaryCpuAbi != null) {
9279                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9280                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9281                            secondaryLibDir, apkName).getAbsolutePath();
9282                }
9283            } else if (asecApp) {
9284                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9285                        .getAbsolutePath();
9286            } else {
9287                final String apkName = deriveCodePathName(codePath);
9288                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9289                        .getAbsolutePath();
9290            }
9291
9292            info.nativeLibraryRootRequiresIsa = false;
9293            info.nativeLibraryDir = info.nativeLibraryRootDir;
9294        } else {
9295            // Cluster install
9296            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9297            info.nativeLibraryRootRequiresIsa = true;
9298
9299            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9300                    getPrimaryInstructionSet(info)).getAbsolutePath();
9301
9302            if (info.secondaryCpuAbi != null) {
9303                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9304                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9305            }
9306        }
9307    }
9308
9309    /**
9310     * Calculate the abis and roots for a bundled app. These can uniquely
9311     * be determined from the contents of the system partition, i.e whether
9312     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9313     * of this information, and instead assume that the system was built
9314     * sensibly.
9315     */
9316    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9317                                           PackageSetting pkgSetting) {
9318        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9319
9320        // If "/system/lib64/apkname" exists, assume that is the per-package
9321        // native library directory to use; otherwise use "/system/lib/apkname".
9322        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9323        setBundledAppAbi(pkg, apkRoot, apkName);
9324        // pkgSetting might be null during rescan following uninstall of updates
9325        // to a bundled app, so accommodate that possibility.  The settings in
9326        // that case will be established later from the parsed package.
9327        //
9328        // If the settings aren't null, sync them up with what we've just derived.
9329        // note that apkRoot isn't stored in the package settings.
9330        if (pkgSetting != null) {
9331            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9332            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9333        }
9334    }
9335
9336    /**
9337     * Deduces the ABI of a bundled app and sets the relevant fields on the
9338     * parsed pkg object.
9339     *
9340     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9341     *        under which system libraries are installed.
9342     * @param apkName the name of the installed package.
9343     */
9344    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9345        final File codeFile = new File(pkg.codePath);
9346
9347        final boolean has64BitLibs;
9348        final boolean has32BitLibs;
9349        if (isApkFile(codeFile)) {
9350            // Monolithic install
9351            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9352            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9353        } else {
9354            // Cluster install
9355            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9356            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9357                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9358                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9359                has64BitLibs = (new File(rootDir, isa)).exists();
9360            } else {
9361                has64BitLibs = false;
9362            }
9363            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9364                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9365                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9366                has32BitLibs = (new File(rootDir, isa)).exists();
9367            } else {
9368                has32BitLibs = false;
9369            }
9370        }
9371
9372        if (has64BitLibs && !has32BitLibs) {
9373            // The package has 64 bit libs, but not 32 bit libs. Its primary
9374            // ABI should be 64 bit. We can safely assume here that the bundled
9375            // native libraries correspond to the most preferred ABI in the list.
9376
9377            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9378            pkg.applicationInfo.secondaryCpuAbi = null;
9379        } else if (has32BitLibs && !has64BitLibs) {
9380            // The package has 32 bit libs but not 64 bit libs. Its primary
9381            // ABI should be 32 bit.
9382
9383            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9384            pkg.applicationInfo.secondaryCpuAbi = null;
9385        } else if (has32BitLibs && has64BitLibs) {
9386            // The application has both 64 and 32 bit bundled libraries. We check
9387            // here that the app declares multiArch support, and warn if it doesn't.
9388            //
9389            // We will be lenient here and record both ABIs. The primary will be the
9390            // ABI that's higher on the list, i.e, a device that's configured to prefer
9391            // 64 bit apps will see a 64 bit primary ABI,
9392
9393            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9394                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9395            }
9396
9397            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9398                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9399                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9400            } else {
9401                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9402                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9403            }
9404        } else {
9405            pkg.applicationInfo.primaryCpuAbi = null;
9406            pkg.applicationInfo.secondaryCpuAbi = null;
9407        }
9408    }
9409
9410    private void killApplication(String pkgName, int appId, String reason) {
9411        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9412    }
9413
9414    private void killApplication(String pkgName, int appId, int userId, String reason) {
9415        // Request the ActivityManager to kill the process(only for existing packages)
9416        // so that we do not end up in a confused state while the user is still using the older
9417        // version of the application while the new one gets installed.
9418        final long token = Binder.clearCallingIdentity();
9419        try {
9420            IActivityManager am = ActivityManagerNative.getDefault();
9421            if (am != null) {
9422                try {
9423                    am.killApplication(pkgName, appId, userId, reason);
9424                } catch (RemoteException e) {
9425                }
9426            }
9427        } finally {
9428            Binder.restoreCallingIdentity(token);
9429        }
9430    }
9431
9432    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9433        // Remove the parent package setting
9434        PackageSetting ps = (PackageSetting) pkg.mExtras;
9435        if (ps != null) {
9436            removePackageLI(ps, chatty);
9437        }
9438        // Remove the child package setting
9439        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9440        for (int i = 0; i < childCount; i++) {
9441            PackageParser.Package childPkg = pkg.childPackages.get(i);
9442            ps = (PackageSetting) childPkg.mExtras;
9443            if (ps != null) {
9444                removePackageLI(ps, chatty);
9445            }
9446        }
9447    }
9448
9449    void removePackageLI(PackageSetting ps, boolean chatty) {
9450        if (DEBUG_INSTALL) {
9451            if (chatty)
9452                Log.d(TAG, "Removing package " + ps.name);
9453        }
9454
9455        // writer
9456        synchronized (mPackages) {
9457            mPackages.remove(ps.name);
9458            final PackageParser.Package pkg = ps.pkg;
9459            if (pkg != null) {
9460                cleanPackageDataStructuresLILPw(pkg, chatty);
9461            }
9462        }
9463    }
9464
9465    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9466        if (DEBUG_INSTALL) {
9467            if (chatty)
9468                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9469        }
9470
9471        // writer
9472        synchronized (mPackages) {
9473            // Remove the parent package
9474            mPackages.remove(pkg.applicationInfo.packageName);
9475            cleanPackageDataStructuresLILPw(pkg, chatty);
9476
9477            // Remove the child packages
9478            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9479            for (int i = 0; i < childCount; i++) {
9480                PackageParser.Package childPkg = pkg.childPackages.get(i);
9481                mPackages.remove(childPkg.applicationInfo.packageName);
9482                cleanPackageDataStructuresLILPw(childPkg, chatty);
9483            }
9484        }
9485    }
9486
9487    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9488        int N = pkg.providers.size();
9489        StringBuilder r = null;
9490        int i;
9491        for (i=0; i<N; i++) {
9492            PackageParser.Provider p = pkg.providers.get(i);
9493            mProviders.removeProvider(p);
9494            if (p.info.authority == null) {
9495
9496                /* There was another ContentProvider with this authority when
9497                 * this app was installed so this authority is null,
9498                 * Ignore it as we don't have to unregister the provider.
9499                 */
9500                continue;
9501            }
9502            String names[] = p.info.authority.split(";");
9503            for (int j = 0; j < names.length; j++) {
9504                if (mProvidersByAuthority.get(names[j]) == p) {
9505                    mProvidersByAuthority.remove(names[j]);
9506                    if (DEBUG_REMOVE) {
9507                        if (chatty)
9508                            Log.d(TAG, "Unregistered content provider: " + names[j]
9509                                    + ", className = " + p.info.name + ", isSyncable = "
9510                                    + p.info.isSyncable);
9511                    }
9512                }
9513            }
9514            if (DEBUG_REMOVE && chatty) {
9515                if (r == null) {
9516                    r = new StringBuilder(256);
9517                } else {
9518                    r.append(' ');
9519                }
9520                r.append(p.info.name);
9521            }
9522        }
9523        if (r != null) {
9524            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9525        }
9526
9527        N = pkg.services.size();
9528        r = null;
9529        for (i=0; i<N; i++) {
9530            PackageParser.Service s = pkg.services.get(i);
9531            mServices.removeService(s);
9532            if (chatty) {
9533                if (r == null) {
9534                    r = new StringBuilder(256);
9535                } else {
9536                    r.append(' ');
9537                }
9538                r.append(s.info.name);
9539            }
9540        }
9541        if (r != null) {
9542            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9543        }
9544
9545        N = pkg.receivers.size();
9546        r = null;
9547        for (i=0; i<N; i++) {
9548            PackageParser.Activity a = pkg.receivers.get(i);
9549            mReceivers.removeActivity(a, "receiver");
9550            if (DEBUG_REMOVE && chatty) {
9551                if (r == null) {
9552                    r = new StringBuilder(256);
9553                } else {
9554                    r.append(' ');
9555                }
9556                r.append(a.info.name);
9557            }
9558        }
9559        if (r != null) {
9560            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9561        }
9562
9563        N = pkg.activities.size();
9564        r = null;
9565        for (i=0; i<N; i++) {
9566            PackageParser.Activity a = pkg.activities.get(i);
9567            mActivities.removeActivity(a, "activity");
9568            if (DEBUG_REMOVE && chatty) {
9569                if (r == null) {
9570                    r = new StringBuilder(256);
9571                } else {
9572                    r.append(' ');
9573                }
9574                r.append(a.info.name);
9575            }
9576        }
9577        if (r != null) {
9578            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9579        }
9580
9581        N = pkg.permissions.size();
9582        r = null;
9583        for (i=0; i<N; i++) {
9584            PackageParser.Permission p = pkg.permissions.get(i);
9585            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9586            if (bp == null) {
9587                bp = mSettings.mPermissionTrees.get(p.info.name);
9588            }
9589            if (bp != null && bp.perm == p) {
9590                bp.perm = null;
9591                if (DEBUG_REMOVE && chatty) {
9592                    if (r == null) {
9593                        r = new StringBuilder(256);
9594                    } else {
9595                        r.append(' ');
9596                    }
9597                    r.append(p.info.name);
9598                }
9599            }
9600            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9601                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9602                if (appOpPkgs != null) {
9603                    appOpPkgs.remove(pkg.packageName);
9604                }
9605            }
9606        }
9607        if (r != null) {
9608            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9609        }
9610
9611        N = pkg.requestedPermissions.size();
9612        r = null;
9613        for (i=0; i<N; i++) {
9614            String perm = pkg.requestedPermissions.get(i);
9615            BasePermission bp = mSettings.mPermissions.get(perm);
9616            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9617                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9618                if (appOpPkgs != null) {
9619                    appOpPkgs.remove(pkg.packageName);
9620                    if (appOpPkgs.isEmpty()) {
9621                        mAppOpPermissionPackages.remove(perm);
9622                    }
9623                }
9624            }
9625        }
9626        if (r != null) {
9627            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9628        }
9629
9630        N = pkg.instrumentation.size();
9631        r = null;
9632        for (i=0; i<N; i++) {
9633            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9634            mInstrumentation.remove(a.getComponentName());
9635            if (DEBUG_REMOVE && chatty) {
9636                if (r == null) {
9637                    r = new StringBuilder(256);
9638                } else {
9639                    r.append(' ');
9640                }
9641                r.append(a.info.name);
9642            }
9643        }
9644        if (r != null) {
9645            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9646        }
9647
9648        r = null;
9649        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9650            // Only system apps can hold shared libraries.
9651            if (pkg.libraryNames != null) {
9652                for (i=0; i<pkg.libraryNames.size(); i++) {
9653                    String name = pkg.libraryNames.get(i);
9654                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9655                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9656                        mSharedLibraries.remove(name);
9657                        if (DEBUG_REMOVE && chatty) {
9658                            if (r == null) {
9659                                r = new StringBuilder(256);
9660                            } else {
9661                                r.append(' ');
9662                            }
9663                            r.append(name);
9664                        }
9665                    }
9666                }
9667            }
9668        }
9669        if (r != null) {
9670            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9671        }
9672    }
9673
9674    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9675        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9676            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9677                return true;
9678            }
9679        }
9680        return false;
9681    }
9682
9683    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9684    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9685    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9686
9687    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9688        // Update the parent permissions
9689        updatePermissionsLPw(pkg.packageName, pkg, flags);
9690        // Update the child permissions
9691        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9692        for (int i = 0; i < childCount; i++) {
9693            PackageParser.Package childPkg = pkg.childPackages.get(i);
9694            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9695        }
9696    }
9697
9698    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9699            int flags) {
9700        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9701        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9702    }
9703
9704    private void updatePermissionsLPw(String changingPkg,
9705            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9706        // Make sure there are no dangling permission trees.
9707        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9708        while (it.hasNext()) {
9709            final BasePermission bp = it.next();
9710            if (bp.packageSetting == null) {
9711                // We may not yet have parsed the package, so just see if
9712                // we still know about its settings.
9713                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9714            }
9715            if (bp.packageSetting == null) {
9716                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9717                        + " from package " + bp.sourcePackage);
9718                it.remove();
9719            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9720                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9721                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9722                            + " from package " + bp.sourcePackage);
9723                    flags |= UPDATE_PERMISSIONS_ALL;
9724                    it.remove();
9725                }
9726            }
9727        }
9728
9729        // Make sure all dynamic permissions have been assigned to a package,
9730        // and make sure there are no dangling permissions.
9731        it = mSettings.mPermissions.values().iterator();
9732        while (it.hasNext()) {
9733            final BasePermission bp = it.next();
9734            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9735                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9736                        + bp.name + " pkg=" + bp.sourcePackage
9737                        + " info=" + bp.pendingInfo);
9738                if (bp.packageSetting == null && bp.pendingInfo != null) {
9739                    final BasePermission tree = findPermissionTreeLP(bp.name);
9740                    if (tree != null && tree.perm != null) {
9741                        bp.packageSetting = tree.packageSetting;
9742                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9743                                new PermissionInfo(bp.pendingInfo));
9744                        bp.perm.info.packageName = tree.perm.info.packageName;
9745                        bp.perm.info.name = bp.name;
9746                        bp.uid = tree.uid;
9747                    }
9748                }
9749            }
9750            if (bp.packageSetting == null) {
9751                // We may not yet have parsed the package, so just see if
9752                // we still know about its settings.
9753                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9754            }
9755            if (bp.packageSetting == null) {
9756                Slog.w(TAG, "Removing dangling permission: " + bp.name
9757                        + " from package " + bp.sourcePackage);
9758                it.remove();
9759            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9760                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9761                    Slog.i(TAG, "Removing old permission: " + bp.name
9762                            + " from package " + bp.sourcePackage);
9763                    flags |= UPDATE_PERMISSIONS_ALL;
9764                    it.remove();
9765                }
9766            }
9767        }
9768
9769        // Now update the permissions for all packages, in particular
9770        // replace the granted permissions of the system packages.
9771        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9772            for (PackageParser.Package pkg : mPackages.values()) {
9773                if (pkg != pkgInfo) {
9774                    // Only replace for packages on requested volume
9775                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9776                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9777                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9778                    grantPermissionsLPw(pkg, replace, changingPkg);
9779                }
9780            }
9781        }
9782
9783        if (pkgInfo != null) {
9784            // Only replace for packages on requested volume
9785            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9786            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9787                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9788            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9789        }
9790    }
9791
9792    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9793            String packageOfInterest) {
9794        // IMPORTANT: There are two types of permissions: install and runtime.
9795        // Install time permissions are granted when the app is installed to
9796        // all device users and users added in the future. Runtime permissions
9797        // are granted at runtime explicitly to specific users. Normal and signature
9798        // protected permissions are install time permissions. Dangerous permissions
9799        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9800        // otherwise they are runtime permissions. This function does not manage
9801        // runtime permissions except for the case an app targeting Lollipop MR1
9802        // being upgraded to target a newer SDK, in which case dangerous permissions
9803        // are transformed from install time to runtime ones.
9804
9805        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9806        if (ps == null) {
9807            return;
9808        }
9809
9810        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9811
9812        PermissionsState permissionsState = ps.getPermissionsState();
9813        PermissionsState origPermissions = permissionsState;
9814
9815        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9816
9817        boolean runtimePermissionsRevoked = false;
9818        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9819
9820        boolean changedInstallPermission = false;
9821
9822        if (replace) {
9823            ps.installPermissionsFixed = false;
9824            if (!ps.isSharedUser()) {
9825                origPermissions = new PermissionsState(permissionsState);
9826                permissionsState.reset();
9827            } else {
9828                // We need to know only about runtime permission changes since the
9829                // calling code always writes the install permissions state but
9830                // the runtime ones are written only if changed. The only cases of
9831                // changed runtime permissions here are promotion of an install to
9832                // runtime and revocation of a runtime from a shared user.
9833                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9834                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9835                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9836                    runtimePermissionsRevoked = true;
9837                }
9838            }
9839        }
9840
9841        permissionsState.setGlobalGids(mGlobalGids);
9842
9843        final int N = pkg.requestedPermissions.size();
9844        for (int i=0; i<N; i++) {
9845            final String name = pkg.requestedPermissions.get(i);
9846            final BasePermission bp = mSettings.mPermissions.get(name);
9847
9848            if (DEBUG_INSTALL) {
9849                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9850            }
9851
9852            if (bp == null || bp.packageSetting == null) {
9853                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9854                    Slog.w(TAG, "Unknown permission " + name
9855                            + " in package " + pkg.packageName);
9856                }
9857                continue;
9858            }
9859
9860            final String perm = bp.name;
9861            boolean allowedSig = false;
9862            int grant = GRANT_DENIED;
9863
9864            // Keep track of app op permissions.
9865            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9866                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9867                if (pkgs == null) {
9868                    pkgs = new ArraySet<>();
9869                    mAppOpPermissionPackages.put(bp.name, pkgs);
9870                }
9871                pkgs.add(pkg.packageName);
9872            }
9873
9874            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9875            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9876                    >= Build.VERSION_CODES.M;
9877            switch (level) {
9878                case PermissionInfo.PROTECTION_NORMAL: {
9879                    // For all apps normal permissions are install time ones.
9880                    grant = GRANT_INSTALL;
9881                } break;
9882
9883                case PermissionInfo.PROTECTION_DANGEROUS: {
9884                    // If a permission review is required for legacy apps we represent
9885                    // their permissions as always granted runtime ones since we need
9886                    // to keep the review required permission flag per user while an
9887                    // install permission's state is shared across all users.
9888                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9889                        // For legacy apps dangerous permissions are install time ones.
9890                        grant = GRANT_INSTALL;
9891                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9892                        // For legacy apps that became modern, install becomes runtime.
9893                        grant = GRANT_UPGRADE;
9894                    } else if (mPromoteSystemApps
9895                            && isSystemApp(ps)
9896                            && mExistingSystemPackages.contains(ps.name)) {
9897                        // For legacy system apps, install becomes runtime.
9898                        // We cannot check hasInstallPermission() for system apps since those
9899                        // permissions were granted implicitly and not persisted pre-M.
9900                        grant = GRANT_UPGRADE;
9901                    } else {
9902                        // For modern apps keep runtime permissions unchanged.
9903                        grant = GRANT_RUNTIME;
9904                    }
9905                } break;
9906
9907                case PermissionInfo.PROTECTION_SIGNATURE: {
9908                    // For all apps signature permissions are install time ones.
9909                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9910                    if (allowedSig) {
9911                        grant = GRANT_INSTALL;
9912                    }
9913                } break;
9914            }
9915
9916            if (DEBUG_INSTALL) {
9917                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9918            }
9919
9920            if (grant != GRANT_DENIED) {
9921                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9922                    // If this is an existing, non-system package, then
9923                    // we can't add any new permissions to it.
9924                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9925                        // Except...  if this is a permission that was added
9926                        // to the platform (note: need to only do this when
9927                        // updating the platform).
9928                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9929                            grant = GRANT_DENIED;
9930                        }
9931                    }
9932                }
9933
9934                switch (grant) {
9935                    case GRANT_INSTALL: {
9936                        // Revoke this as runtime permission to handle the case of
9937                        // a runtime permission being downgraded to an install one.
9938                        // Also in permission review mode we keep dangerous permissions
9939                        // for legacy apps
9940                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9941                            if (origPermissions.getRuntimePermissionState(
9942                                    bp.name, userId) != null) {
9943                                // Revoke the runtime permission and clear the flags.
9944                                origPermissions.revokeRuntimePermission(bp, userId);
9945                                origPermissions.updatePermissionFlags(bp, userId,
9946                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9947                                // If we revoked a permission permission, we have to write.
9948                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9949                                        changedRuntimePermissionUserIds, userId);
9950                            }
9951                        }
9952                        // Grant an install permission.
9953                        if (permissionsState.grantInstallPermission(bp) !=
9954                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9955                            changedInstallPermission = true;
9956                        }
9957                    } break;
9958
9959                    case GRANT_RUNTIME: {
9960                        // Grant previously granted runtime permissions.
9961                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9962                            PermissionState permissionState = origPermissions
9963                                    .getRuntimePermissionState(bp.name, userId);
9964                            int flags = permissionState != null
9965                                    ? permissionState.getFlags() : 0;
9966                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9967                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9968                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9969                                    // If we cannot put the permission as it was, we have to write.
9970                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9971                                            changedRuntimePermissionUserIds, userId);
9972                                }
9973                                // If the app supports runtime permissions no need for a review.
9974                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9975                                        && appSupportsRuntimePermissions
9976                                        && (flags & PackageManager
9977                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9978                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9979                                    // Since we changed the flags, we have to write.
9980                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9981                                            changedRuntimePermissionUserIds, userId);
9982                                }
9983                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9984                                    && !appSupportsRuntimePermissions) {
9985                                // For legacy apps that need a permission review, every new
9986                                // runtime permission is granted but it is pending a review.
9987                                // We also need to review only platform defined runtime
9988                                // permissions as these are the only ones the platform knows
9989                                // how to disable the API to simulate revocation as legacy
9990                                // apps don't expect to run with revoked permissions.
9991                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
9992                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9993                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9994                                        // We changed the flags, hence have to write.
9995                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9996                                                changedRuntimePermissionUserIds, userId);
9997                                    }
9998                                }
9999                                if (permissionsState.grantRuntimePermission(bp, userId)
10000                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10001                                    // We changed the permission, hence have to write.
10002                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10003                                            changedRuntimePermissionUserIds, userId);
10004                                }
10005                            }
10006                            // Propagate the permission flags.
10007                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10008                        }
10009                    } break;
10010
10011                    case GRANT_UPGRADE: {
10012                        // Grant runtime permissions for a previously held install permission.
10013                        PermissionState permissionState = origPermissions
10014                                .getInstallPermissionState(bp.name);
10015                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10016
10017                        if (origPermissions.revokeInstallPermission(bp)
10018                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10019                            // We will be transferring the permission flags, so clear them.
10020                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10021                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10022                            changedInstallPermission = true;
10023                        }
10024
10025                        // If the permission is not to be promoted to runtime we ignore it and
10026                        // also its other flags as they are not applicable to install permissions.
10027                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10028                            for (int userId : currentUserIds) {
10029                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10030                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10031                                    // Transfer the permission flags.
10032                                    permissionsState.updatePermissionFlags(bp, userId,
10033                                            flags, flags);
10034                                    // If we granted the permission, we have to write.
10035                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10036                                            changedRuntimePermissionUserIds, userId);
10037                                }
10038                            }
10039                        }
10040                    } break;
10041
10042                    default: {
10043                        if (packageOfInterest == null
10044                                || packageOfInterest.equals(pkg.packageName)) {
10045                            Slog.w(TAG, "Not granting permission " + perm
10046                                    + " to package " + pkg.packageName
10047                                    + " because it was previously installed without");
10048                        }
10049                    } break;
10050                }
10051            } else {
10052                if (permissionsState.revokeInstallPermission(bp) !=
10053                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10054                    // Also drop the permission flags.
10055                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10056                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10057                    changedInstallPermission = true;
10058                    Slog.i(TAG, "Un-granting permission " + perm
10059                            + " from package " + pkg.packageName
10060                            + " (protectionLevel=" + bp.protectionLevel
10061                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10062                            + ")");
10063                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10064                    // Don't print warning for app op permissions, since it is fine for them
10065                    // not to be granted, there is a UI for the user to decide.
10066                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10067                        Slog.w(TAG, "Not granting permission " + perm
10068                                + " to package " + pkg.packageName
10069                                + " (protectionLevel=" + bp.protectionLevel
10070                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10071                                + ")");
10072                    }
10073                }
10074            }
10075        }
10076
10077        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10078                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10079            // This is the first that we have heard about this package, so the
10080            // permissions we have now selected are fixed until explicitly
10081            // changed.
10082            ps.installPermissionsFixed = true;
10083        }
10084
10085        // Persist the runtime permissions state for users with changes. If permissions
10086        // were revoked because no app in the shared user declares them we have to
10087        // write synchronously to avoid losing runtime permissions state.
10088        for (int userId : changedRuntimePermissionUserIds) {
10089            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10090        }
10091
10092        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10093    }
10094
10095    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10096        boolean allowed = false;
10097        final int NP = PackageParser.NEW_PERMISSIONS.length;
10098        for (int ip=0; ip<NP; ip++) {
10099            final PackageParser.NewPermissionInfo npi
10100                    = PackageParser.NEW_PERMISSIONS[ip];
10101            if (npi.name.equals(perm)
10102                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10103                allowed = true;
10104                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10105                        + pkg.packageName);
10106                break;
10107            }
10108        }
10109        return allowed;
10110    }
10111
10112    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10113            BasePermission bp, PermissionsState origPermissions) {
10114        boolean allowed;
10115        allowed = (compareSignatures(
10116                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10117                        == PackageManager.SIGNATURE_MATCH)
10118                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10119                        == PackageManager.SIGNATURE_MATCH);
10120        if (!allowed && (bp.protectionLevel
10121                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10122            if (isSystemApp(pkg)) {
10123                // For updated system applications, a system permission
10124                // is granted only if it had been defined by the original application.
10125                if (pkg.isUpdatedSystemApp()) {
10126                    final PackageSetting sysPs = mSettings
10127                            .getDisabledSystemPkgLPr(pkg.packageName);
10128                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10129                        // If the original was granted this permission, we take
10130                        // that grant decision as read and propagate it to the
10131                        // update.
10132                        if (sysPs.isPrivileged()) {
10133                            allowed = true;
10134                        }
10135                    } else {
10136                        // The system apk may have been updated with an older
10137                        // version of the one on the data partition, but which
10138                        // granted a new system permission that it didn't have
10139                        // before.  In this case we do want to allow the app to
10140                        // now get the new permission if the ancestral apk is
10141                        // privileged to get it.
10142                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10143                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10144                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10145                                    allowed = true;
10146                                    break;
10147                                }
10148                            }
10149                        }
10150                        // Also if a privileged parent package on the system image or any of
10151                        // its children requested a privileged permission, the updated child
10152                        // packages can also get the permission.
10153                        if (pkg.parentPackage != null) {
10154                            final PackageSetting disabledSysParentPs = mSettings
10155                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10156                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10157                                    && disabledSysParentPs.isPrivileged()) {
10158                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10159                                    allowed = true;
10160                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10161                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10162                                    for (int i = 0; i < count; i++) {
10163                                        PackageParser.Package disabledSysChildPkg =
10164                                                disabledSysParentPs.pkg.childPackages.get(i);
10165                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10166                                                perm)) {
10167                                            allowed = true;
10168                                            break;
10169                                        }
10170                                    }
10171                                }
10172                            }
10173                        }
10174                    }
10175                } else {
10176                    allowed = isPrivilegedApp(pkg);
10177                }
10178            }
10179        }
10180        if (!allowed) {
10181            if (!allowed && (bp.protectionLevel
10182                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10183                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10184                // If this was a previously normal/dangerous permission that got moved
10185                // to a system permission as part of the runtime permission redesign, then
10186                // we still want to blindly grant it to old apps.
10187                allowed = true;
10188            }
10189            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10190                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10191                // If this permission is to be granted to the system installer and
10192                // this app is an installer, then it gets the permission.
10193                allowed = true;
10194            }
10195            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10196                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10197                // If this permission is to be granted to the system verifier and
10198                // this app is a verifier, then it gets the permission.
10199                allowed = true;
10200            }
10201            if (!allowed && (bp.protectionLevel
10202                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10203                    && isSystemApp(pkg)) {
10204                // Any pre-installed system app is allowed to get this permission.
10205                allowed = true;
10206            }
10207            if (!allowed && (bp.protectionLevel
10208                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10209                // For development permissions, a development permission
10210                // is granted only if it was already granted.
10211                allowed = origPermissions.hasInstallPermission(perm);
10212            }
10213            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10214                    && pkg.packageName.equals(mSetupWizardPackage)) {
10215                // If this permission is to be granted to the system setup wizard and
10216                // this app is a setup wizard, then it gets the permission.
10217                allowed = true;
10218            }
10219        }
10220        return allowed;
10221    }
10222
10223    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10224        final int permCount = pkg.requestedPermissions.size();
10225        for (int j = 0; j < permCount; j++) {
10226            String requestedPermission = pkg.requestedPermissions.get(j);
10227            if (permission.equals(requestedPermission)) {
10228                return true;
10229            }
10230        }
10231        return false;
10232    }
10233
10234    final class ActivityIntentResolver
10235            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10236        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10237                boolean defaultOnly, int userId) {
10238            if (!sUserManager.exists(userId)) return null;
10239            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10240            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10241        }
10242
10243        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10244                int userId) {
10245            if (!sUserManager.exists(userId)) return null;
10246            mFlags = flags;
10247            return super.queryIntent(intent, resolvedType,
10248                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10249        }
10250
10251        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10252                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10253            if (!sUserManager.exists(userId)) return null;
10254            if (packageActivities == null) {
10255                return null;
10256            }
10257            mFlags = flags;
10258            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10259            final int N = packageActivities.size();
10260            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10261                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10262
10263            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10264            for (int i = 0; i < N; ++i) {
10265                intentFilters = packageActivities.get(i).intents;
10266                if (intentFilters != null && intentFilters.size() > 0) {
10267                    PackageParser.ActivityIntentInfo[] array =
10268                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10269                    intentFilters.toArray(array);
10270                    listCut.add(array);
10271                }
10272            }
10273            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10274        }
10275
10276        /**
10277         * Finds a privileged activity that matches the specified activity names.
10278         */
10279        private PackageParser.Activity findMatchingActivity(
10280                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10281            for (PackageParser.Activity sysActivity : activityList) {
10282                if (sysActivity.info.name.equals(activityInfo.name)) {
10283                    return sysActivity;
10284                }
10285                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10286                    return sysActivity;
10287                }
10288                if (sysActivity.info.targetActivity != null) {
10289                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10290                        return sysActivity;
10291                    }
10292                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10293                        return sysActivity;
10294                    }
10295                }
10296            }
10297            return null;
10298        }
10299
10300        public class IterGenerator<E> {
10301            public Iterator<E> generate(ActivityIntentInfo info) {
10302                return null;
10303            }
10304        }
10305
10306        public class ActionIterGenerator extends IterGenerator<String> {
10307            @Override
10308            public Iterator<String> generate(ActivityIntentInfo info) {
10309                return info.actionsIterator();
10310            }
10311        }
10312
10313        public class CategoriesIterGenerator extends IterGenerator<String> {
10314            @Override
10315            public Iterator<String> generate(ActivityIntentInfo info) {
10316                return info.categoriesIterator();
10317            }
10318        }
10319
10320        public class SchemesIterGenerator extends IterGenerator<String> {
10321            @Override
10322            public Iterator<String> generate(ActivityIntentInfo info) {
10323                return info.schemesIterator();
10324            }
10325        }
10326
10327        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10328            @Override
10329            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10330                return info.authoritiesIterator();
10331            }
10332        }
10333
10334        /**
10335         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10336         * MODIFIED. Do not pass in a list that should not be changed.
10337         */
10338        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10339                IterGenerator<T> generator, Iterator<T> searchIterator) {
10340            // loop through the set of actions; every one must be found in the intent filter
10341            while (searchIterator.hasNext()) {
10342                // we must have at least one filter in the list to consider a match
10343                if (intentList.size() == 0) {
10344                    break;
10345                }
10346
10347                final T searchAction = searchIterator.next();
10348
10349                // loop through the set of intent filters
10350                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10351                while (intentIter.hasNext()) {
10352                    final ActivityIntentInfo intentInfo = intentIter.next();
10353                    boolean selectionFound = false;
10354
10355                    // loop through the intent filter's selection criteria; at least one
10356                    // of them must match the searched criteria
10357                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10358                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10359                        final T intentSelection = intentSelectionIter.next();
10360                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10361                            selectionFound = true;
10362                            break;
10363                        }
10364                    }
10365
10366                    // the selection criteria wasn't found in this filter's set; this filter
10367                    // is not a potential match
10368                    if (!selectionFound) {
10369                        intentIter.remove();
10370                    }
10371                }
10372            }
10373        }
10374
10375        private boolean isProtectedAction(ActivityIntentInfo filter) {
10376            final Iterator<String> actionsIter = filter.actionsIterator();
10377            while (actionsIter != null && actionsIter.hasNext()) {
10378                final String filterAction = actionsIter.next();
10379                if (PROTECTED_ACTIONS.contains(filterAction)) {
10380                    return true;
10381                }
10382            }
10383            return false;
10384        }
10385
10386        /**
10387         * Adjusts the priority of the given intent filter according to policy.
10388         * <p>
10389         * <ul>
10390         * <li>The priority for non privileged applications is capped to '0'</li>
10391         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10392         * <li>The priority for unbundled updates to privileged applications is capped to the
10393         *      priority defined on the system partition</li>
10394         * </ul>
10395         * <p>
10396         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10397         * allowed to obtain any priority on any action.
10398         */
10399        private void adjustPriority(
10400                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10401            // nothing to do; priority is fine as-is
10402            if (intent.getPriority() <= 0) {
10403                return;
10404            }
10405
10406            final ActivityInfo activityInfo = intent.activity.info;
10407            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10408
10409            final boolean privilegedApp =
10410                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10411            if (!privilegedApp) {
10412                // non-privileged applications can never define a priority >0
10413                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10414                        + " package: " + applicationInfo.packageName
10415                        + " activity: " + intent.activity.className
10416                        + " origPrio: " + intent.getPriority());
10417                intent.setPriority(0);
10418                return;
10419            }
10420
10421            if (systemActivities == null) {
10422                // the system package is not disabled; we're parsing the system partition
10423                if (isProtectedAction(intent)) {
10424                    if (mDeferProtectedFilters) {
10425                        // We can't deal with these just yet. No component should ever obtain a
10426                        // >0 priority for a protected actions, with ONE exception -- the setup
10427                        // wizard. The setup wizard, however, cannot be known until we're able to
10428                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10429                        // until all intent filters have been processed. Chicken, meet egg.
10430                        // Let the filter temporarily have a high priority and rectify the
10431                        // priorities after all system packages have been scanned.
10432                        mProtectedFilters.add(intent);
10433                        if (DEBUG_FILTERS) {
10434                            Slog.i(TAG, "Protected action; save for later;"
10435                                    + " package: " + applicationInfo.packageName
10436                                    + " activity: " + intent.activity.className
10437                                    + " origPrio: " + intent.getPriority());
10438                        }
10439                        return;
10440                    } else {
10441                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10442                            Slog.i(TAG, "No setup wizard;"
10443                                + " All protected intents capped to priority 0");
10444                        }
10445                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10446                            if (DEBUG_FILTERS) {
10447                                Slog.i(TAG, "Found setup wizard;"
10448                                    + " allow priority " + intent.getPriority() + ";"
10449                                    + " package: " + intent.activity.info.packageName
10450                                    + " activity: " + intent.activity.className
10451                                    + " priority: " + intent.getPriority());
10452                            }
10453                            // setup wizard gets whatever it wants
10454                            return;
10455                        }
10456                        Slog.w(TAG, "Protected action; cap priority to 0;"
10457                                + " package: " + intent.activity.info.packageName
10458                                + " activity: " + intent.activity.className
10459                                + " origPrio: " + intent.getPriority());
10460                        intent.setPriority(0);
10461                        return;
10462                    }
10463                }
10464                // privileged apps on the system image get whatever priority they request
10465                return;
10466            }
10467
10468            // privileged app unbundled update ... try to find the same activity
10469            final PackageParser.Activity foundActivity =
10470                    findMatchingActivity(systemActivities, activityInfo);
10471            if (foundActivity == null) {
10472                // this is a new activity; it cannot obtain >0 priority
10473                if (DEBUG_FILTERS) {
10474                    Slog.i(TAG, "New activity; cap priority to 0;"
10475                            + " package: " + applicationInfo.packageName
10476                            + " activity: " + intent.activity.className
10477                            + " origPrio: " + intent.getPriority());
10478                }
10479                intent.setPriority(0);
10480                return;
10481            }
10482
10483            // found activity, now check for filter equivalence
10484
10485            // a shallow copy is enough; we modify the list, not its contents
10486            final List<ActivityIntentInfo> intentListCopy =
10487                    new ArrayList<>(foundActivity.intents);
10488            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10489
10490            // find matching action subsets
10491            final Iterator<String> actionsIterator = intent.actionsIterator();
10492            if (actionsIterator != null) {
10493                getIntentListSubset(
10494                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10495                if (intentListCopy.size() == 0) {
10496                    // no more intents to match; we're not equivalent
10497                    if (DEBUG_FILTERS) {
10498                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10499                                + " package: " + applicationInfo.packageName
10500                                + " activity: " + intent.activity.className
10501                                + " origPrio: " + intent.getPriority());
10502                    }
10503                    intent.setPriority(0);
10504                    return;
10505                }
10506            }
10507
10508            // find matching category subsets
10509            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10510            if (categoriesIterator != null) {
10511                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10512                        categoriesIterator);
10513                if (intentListCopy.size() == 0) {
10514                    // no more intents to match; we're not equivalent
10515                    if (DEBUG_FILTERS) {
10516                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10517                                + " package: " + applicationInfo.packageName
10518                                + " activity: " + intent.activity.className
10519                                + " origPrio: " + intent.getPriority());
10520                    }
10521                    intent.setPriority(0);
10522                    return;
10523                }
10524            }
10525
10526            // find matching schemes subsets
10527            final Iterator<String> schemesIterator = intent.schemesIterator();
10528            if (schemesIterator != null) {
10529                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10530                        schemesIterator);
10531                if (intentListCopy.size() == 0) {
10532                    // no more intents to match; we're not equivalent
10533                    if (DEBUG_FILTERS) {
10534                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10535                                + " package: " + applicationInfo.packageName
10536                                + " activity: " + intent.activity.className
10537                                + " origPrio: " + intent.getPriority());
10538                    }
10539                    intent.setPriority(0);
10540                    return;
10541                }
10542            }
10543
10544            // find matching authorities subsets
10545            final Iterator<IntentFilter.AuthorityEntry>
10546                    authoritiesIterator = intent.authoritiesIterator();
10547            if (authoritiesIterator != null) {
10548                getIntentListSubset(intentListCopy,
10549                        new AuthoritiesIterGenerator(),
10550                        authoritiesIterator);
10551                if (intentListCopy.size() == 0) {
10552                    // no more intents to match; we're not equivalent
10553                    if (DEBUG_FILTERS) {
10554                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10555                                + " package: " + applicationInfo.packageName
10556                                + " activity: " + intent.activity.className
10557                                + " origPrio: " + intent.getPriority());
10558                    }
10559                    intent.setPriority(0);
10560                    return;
10561                }
10562            }
10563
10564            // we found matching filter(s); app gets the max priority of all intents
10565            int cappedPriority = 0;
10566            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10567                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10568            }
10569            if (intent.getPriority() > cappedPriority) {
10570                if (DEBUG_FILTERS) {
10571                    Slog.i(TAG, "Found matching filter(s);"
10572                            + " cap priority to " + cappedPriority + ";"
10573                            + " package: " + applicationInfo.packageName
10574                            + " activity: " + intent.activity.className
10575                            + " origPrio: " + intent.getPriority());
10576                }
10577                intent.setPriority(cappedPriority);
10578                return;
10579            }
10580            // all this for nothing; the requested priority was <= what was on the system
10581        }
10582
10583        public final void addActivity(PackageParser.Activity a, String type) {
10584            mActivities.put(a.getComponentName(), a);
10585            if (DEBUG_SHOW_INFO)
10586                Log.v(
10587                TAG, "  " + type + " " +
10588                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10589            if (DEBUG_SHOW_INFO)
10590                Log.v(TAG, "    Class=" + a.info.name);
10591            final int NI = a.intents.size();
10592            for (int j=0; j<NI; j++) {
10593                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10594                if ("activity".equals(type)) {
10595                    final PackageSetting ps =
10596                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10597                    final List<PackageParser.Activity> systemActivities =
10598                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10599                    adjustPriority(systemActivities, intent);
10600                }
10601                if (DEBUG_SHOW_INFO) {
10602                    Log.v(TAG, "    IntentFilter:");
10603                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10604                }
10605                if (!intent.debugCheck()) {
10606                    Log.w(TAG, "==> For Activity " + a.info.name);
10607                }
10608                addFilter(intent);
10609            }
10610        }
10611
10612        public final void removeActivity(PackageParser.Activity a, String type) {
10613            mActivities.remove(a.getComponentName());
10614            if (DEBUG_SHOW_INFO) {
10615                Log.v(TAG, "  " + type + " "
10616                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10617                                : a.info.name) + ":");
10618                Log.v(TAG, "    Class=" + a.info.name);
10619            }
10620            final int NI = a.intents.size();
10621            for (int j=0; j<NI; j++) {
10622                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10623                if (DEBUG_SHOW_INFO) {
10624                    Log.v(TAG, "    IntentFilter:");
10625                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10626                }
10627                removeFilter(intent);
10628            }
10629        }
10630
10631        @Override
10632        protected boolean allowFilterResult(
10633                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10634            ActivityInfo filterAi = filter.activity.info;
10635            for (int i=dest.size()-1; i>=0; i--) {
10636                ActivityInfo destAi = dest.get(i).activityInfo;
10637                if (destAi.name == filterAi.name
10638                        && destAi.packageName == filterAi.packageName) {
10639                    return false;
10640                }
10641            }
10642            return true;
10643        }
10644
10645        @Override
10646        protected ActivityIntentInfo[] newArray(int size) {
10647            return new ActivityIntentInfo[size];
10648        }
10649
10650        @Override
10651        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10652            if (!sUserManager.exists(userId)) return true;
10653            PackageParser.Package p = filter.activity.owner;
10654            if (p != null) {
10655                PackageSetting ps = (PackageSetting)p.mExtras;
10656                if (ps != null) {
10657                    // System apps are never considered stopped for purposes of
10658                    // filtering, because there may be no way for the user to
10659                    // actually re-launch them.
10660                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10661                            && ps.getStopped(userId);
10662                }
10663            }
10664            return false;
10665        }
10666
10667        @Override
10668        protected boolean isPackageForFilter(String packageName,
10669                PackageParser.ActivityIntentInfo info) {
10670            return packageName.equals(info.activity.owner.packageName);
10671        }
10672
10673        @Override
10674        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10675                int match, int userId) {
10676            if (!sUserManager.exists(userId)) return null;
10677            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10678                return null;
10679            }
10680            final PackageParser.Activity activity = info.activity;
10681            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10682            if (ps == null) {
10683                return null;
10684            }
10685            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10686                    ps.readUserState(userId), userId);
10687            if (ai == null) {
10688                return null;
10689            }
10690            final ResolveInfo res = new ResolveInfo();
10691            res.activityInfo = ai;
10692            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10693                res.filter = info;
10694            }
10695            if (info != null) {
10696                res.handleAllWebDataURI = info.handleAllWebDataURI();
10697            }
10698            res.priority = info.getPriority();
10699            res.preferredOrder = activity.owner.mPreferredOrder;
10700            //System.out.println("Result: " + res.activityInfo.className +
10701            //                   " = " + res.priority);
10702            res.match = match;
10703            res.isDefault = info.hasDefault;
10704            res.labelRes = info.labelRes;
10705            res.nonLocalizedLabel = info.nonLocalizedLabel;
10706            if (userNeedsBadging(userId)) {
10707                res.noResourceId = true;
10708            } else {
10709                res.icon = info.icon;
10710            }
10711            res.iconResourceId = info.icon;
10712            res.system = res.activityInfo.applicationInfo.isSystemApp();
10713            return res;
10714        }
10715
10716        @Override
10717        protected void sortResults(List<ResolveInfo> results) {
10718            Collections.sort(results, mResolvePrioritySorter);
10719        }
10720
10721        @Override
10722        protected void dumpFilter(PrintWriter out, String prefix,
10723                PackageParser.ActivityIntentInfo filter) {
10724            out.print(prefix); out.print(
10725                    Integer.toHexString(System.identityHashCode(filter.activity)));
10726                    out.print(' ');
10727                    filter.activity.printComponentShortName(out);
10728                    out.print(" filter ");
10729                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10730        }
10731
10732        @Override
10733        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10734            return filter.activity;
10735        }
10736
10737        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10738            PackageParser.Activity activity = (PackageParser.Activity)label;
10739            out.print(prefix); out.print(
10740                    Integer.toHexString(System.identityHashCode(activity)));
10741                    out.print(' ');
10742                    activity.printComponentShortName(out);
10743            if (count > 1) {
10744                out.print(" ("); out.print(count); out.print(" filters)");
10745            }
10746            out.println();
10747        }
10748
10749        // Keys are String (activity class name), values are Activity.
10750        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10751                = new ArrayMap<ComponentName, PackageParser.Activity>();
10752        private int mFlags;
10753    }
10754
10755    private final class ServiceIntentResolver
10756            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10757        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10758                boolean defaultOnly, int userId) {
10759            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10760            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10761        }
10762
10763        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10764                int userId) {
10765            if (!sUserManager.exists(userId)) return null;
10766            mFlags = flags;
10767            return super.queryIntent(intent, resolvedType,
10768                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10769        }
10770
10771        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10772                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10773            if (!sUserManager.exists(userId)) return null;
10774            if (packageServices == null) {
10775                return null;
10776            }
10777            mFlags = flags;
10778            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10779            final int N = packageServices.size();
10780            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10781                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10782
10783            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10784            for (int i = 0; i < N; ++i) {
10785                intentFilters = packageServices.get(i).intents;
10786                if (intentFilters != null && intentFilters.size() > 0) {
10787                    PackageParser.ServiceIntentInfo[] array =
10788                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10789                    intentFilters.toArray(array);
10790                    listCut.add(array);
10791                }
10792            }
10793            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10794        }
10795
10796        public final void addService(PackageParser.Service s) {
10797            mServices.put(s.getComponentName(), s);
10798            if (DEBUG_SHOW_INFO) {
10799                Log.v(TAG, "  "
10800                        + (s.info.nonLocalizedLabel != null
10801                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10802                Log.v(TAG, "    Class=" + s.info.name);
10803            }
10804            final int NI = s.intents.size();
10805            int j;
10806            for (j=0; j<NI; j++) {
10807                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10808                if (DEBUG_SHOW_INFO) {
10809                    Log.v(TAG, "    IntentFilter:");
10810                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10811                }
10812                if (!intent.debugCheck()) {
10813                    Log.w(TAG, "==> For Service " + s.info.name);
10814                }
10815                addFilter(intent);
10816            }
10817        }
10818
10819        public final void removeService(PackageParser.Service s) {
10820            mServices.remove(s.getComponentName());
10821            if (DEBUG_SHOW_INFO) {
10822                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10823                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10824                Log.v(TAG, "    Class=" + s.info.name);
10825            }
10826            final int NI = s.intents.size();
10827            int j;
10828            for (j=0; j<NI; j++) {
10829                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10830                if (DEBUG_SHOW_INFO) {
10831                    Log.v(TAG, "    IntentFilter:");
10832                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10833                }
10834                removeFilter(intent);
10835            }
10836        }
10837
10838        @Override
10839        protected boolean allowFilterResult(
10840                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10841            ServiceInfo filterSi = filter.service.info;
10842            for (int i=dest.size()-1; i>=0; i--) {
10843                ServiceInfo destAi = dest.get(i).serviceInfo;
10844                if (destAi.name == filterSi.name
10845                        && destAi.packageName == filterSi.packageName) {
10846                    return false;
10847                }
10848            }
10849            return true;
10850        }
10851
10852        @Override
10853        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10854            return new PackageParser.ServiceIntentInfo[size];
10855        }
10856
10857        @Override
10858        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10859            if (!sUserManager.exists(userId)) return true;
10860            PackageParser.Package p = filter.service.owner;
10861            if (p != null) {
10862                PackageSetting ps = (PackageSetting)p.mExtras;
10863                if (ps != null) {
10864                    // System apps are never considered stopped for purposes of
10865                    // filtering, because there may be no way for the user to
10866                    // actually re-launch them.
10867                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10868                            && ps.getStopped(userId);
10869                }
10870            }
10871            return false;
10872        }
10873
10874        @Override
10875        protected boolean isPackageForFilter(String packageName,
10876                PackageParser.ServiceIntentInfo info) {
10877            return packageName.equals(info.service.owner.packageName);
10878        }
10879
10880        @Override
10881        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10882                int match, int userId) {
10883            if (!sUserManager.exists(userId)) return null;
10884            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10885            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10886                return null;
10887            }
10888            final PackageParser.Service service = info.service;
10889            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10890            if (ps == null) {
10891                return null;
10892            }
10893            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10894                    ps.readUserState(userId), userId);
10895            if (si == null) {
10896                return null;
10897            }
10898            final ResolveInfo res = new ResolveInfo();
10899            res.serviceInfo = si;
10900            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10901                res.filter = filter;
10902            }
10903            res.priority = info.getPriority();
10904            res.preferredOrder = service.owner.mPreferredOrder;
10905            res.match = match;
10906            res.isDefault = info.hasDefault;
10907            res.labelRes = info.labelRes;
10908            res.nonLocalizedLabel = info.nonLocalizedLabel;
10909            res.icon = info.icon;
10910            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10911            return res;
10912        }
10913
10914        @Override
10915        protected void sortResults(List<ResolveInfo> results) {
10916            Collections.sort(results, mResolvePrioritySorter);
10917        }
10918
10919        @Override
10920        protected void dumpFilter(PrintWriter out, String prefix,
10921                PackageParser.ServiceIntentInfo filter) {
10922            out.print(prefix); out.print(
10923                    Integer.toHexString(System.identityHashCode(filter.service)));
10924                    out.print(' ');
10925                    filter.service.printComponentShortName(out);
10926                    out.print(" filter ");
10927                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10928        }
10929
10930        @Override
10931        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10932            return filter.service;
10933        }
10934
10935        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10936            PackageParser.Service service = (PackageParser.Service)label;
10937            out.print(prefix); out.print(
10938                    Integer.toHexString(System.identityHashCode(service)));
10939                    out.print(' ');
10940                    service.printComponentShortName(out);
10941            if (count > 1) {
10942                out.print(" ("); out.print(count); out.print(" filters)");
10943            }
10944            out.println();
10945        }
10946
10947//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10948//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10949//            final List<ResolveInfo> retList = Lists.newArrayList();
10950//            while (i.hasNext()) {
10951//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10952//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10953//                    retList.add(resolveInfo);
10954//                }
10955//            }
10956//            return retList;
10957//        }
10958
10959        // Keys are String (activity class name), values are Activity.
10960        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10961                = new ArrayMap<ComponentName, PackageParser.Service>();
10962        private int mFlags;
10963    };
10964
10965    private final class ProviderIntentResolver
10966            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10967        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10968                boolean defaultOnly, int userId) {
10969            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10970            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10971        }
10972
10973        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10974                int userId) {
10975            if (!sUserManager.exists(userId))
10976                return null;
10977            mFlags = flags;
10978            return super.queryIntent(intent, resolvedType,
10979                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10980        }
10981
10982        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10983                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10984            if (!sUserManager.exists(userId))
10985                return null;
10986            if (packageProviders == null) {
10987                return null;
10988            }
10989            mFlags = flags;
10990            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10991            final int N = packageProviders.size();
10992            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10993                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10994
10995            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10996            for (int i = 0; i < N; ++i) {
10997                intentFilters = packageProviders.get(i).intents;
10998                if (intentFilters != null && intentFilters.size() > 0) {
10999                    PackageParser.ProviderIntentInfo[] array =
11000                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11001                    intentFilters.toArray(array);
11002                    listCut.add(array);
11003                }
11004            }
11005            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11006        }
11007
11008        public final void addProvider(PackageParser.Provider p) {
11009            if (mProviders.containsKey(p.getComponentName())) {
11010                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11011                return;
11012            }
11013
11014            mProviders.put(p.getComponentName(), p);
11015            if (DEBUG_SHOW_INFO) {
11016                Log.v(TAG, "  "
11017                        + (p.info.nonLocalizedLabel != null
11018                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11019                Log.v(TAG, "    Class=" + p.info.name);
11020            }
11021            final int NI = p.intents.size();
11022            int j;
11023            for (j = 0; j < NI; j++) {
11024                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11025                if (DEBUG_SHOW_INFO) {
11026                    Log.v(TAG, "    IntentFilter:");
11027                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11028                }
11029                if (!intent.debugCheck()) {
11030                    Log.w(TAG, "==> For Provider " + p.info.name);
11031                }
11032                addFilter(intent);
11033            }
11034        }
11035
11036        public final void removeProvider(PackageParser.Provider p) {
11037            mProviders.remove(p.getComponentName());
11038            if (DEBUG_SHOW_INFO) {
11039                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11040                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11041                Log.v(TAG, "    Class=" + p.info.name);
11042            }
11043            final int NI = p.intents.size();
11044            int j;
11045            for (j = 0; j < NI; j++) {
11046                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11047                if (DEBUG_SHOW_INFO) {
11048                    Log.v(TAG, "    IntentFilter:");
11049                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11050                }
11051                removeFilter(intent);
11052            }
11053        }
11054
11055        @Override
11056        protected boolean allowFilterResult(
11057                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11058            ProviderInfo filterPi = filter.provider.info;
11059            for (int i = dest.size() - 1; i >= 0; i--) {
11060                ProviderInfo destPi = dest.get(i).providerInfo;
11061                if (destPi.name == filterPi.name
11062                        && destPi.packageName == filterPi.packageName) {
11063                    return false;
11064                }
11065            }
11066            return true;
11067        }
11068
11069        @Override
11070        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11071            return new PackageParser.ProviderIntentInfo[size];
11072        }
11073
11074        @Override
11075        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11076            if (!sUserManager.exists(userId))
11077                return true;
11078            PackageParser.Package p = filter.provider.owner;
11079            if (p != null) {
11080                PackageSetting ps = (PackageSetting) p.mExtras;
11081                if (ps != null) {
11082                    // System apps are never considered stopped for purposes of
11083                    // filtering, because there may be no way for the user to
11084                    // actually re-launch them.
11085                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11086                            && ps.getStopped(userId);
11087                }
11088            }
11089            return false;
11090        }
11091
11092        @Override
11093        protected boolean isPackageForFilter(String packageName,
11094                PackageParser.ProviderIntentInfo info) {
11095            return packageName.equals(info.provider.owner.packageName);
11096        }
11097
11098        @Override
11099        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11100                int match, int userId) {
11101            if (!sUserManager.exists(userId))
11102                return null;
11103            final PackageParser.ProviderIntentInfo info = filter;
11104            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11105                return null;
11106            }
11107            final PackageParser.Provider provider = info.provider;
11108            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11109            if (ps == null) {
11110                return null;
11111            }
11112            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11113                    ps.readUserState(userId), userId);
11114            if (pi == null) {
11115                return null;
11116            }
11117            final ResolveInfo res = new ResolveInfo();
11118            res.providerInfo = pi;
11119            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11120                res.filter = filter;
11121            }
11122            res.priority = info.getPriority();
11123            res.preferredOrder = provider.owner.mPreferredOrder;
11124            res.match = match;
11125            res.isDefault = info.hasDefault;
11126            res.labelRes = info.labelRes;
11127            res.nonLocalizedLabel = info.nonLocalizedLabel;
11128            res.icon = info.icon;
11129            res.system = res.providerInfo.applicationInfo.isSystemApp();
11130            return res;
11131        }
11132
11133        @Override
11134        protected void sortResults(List<ResolveInfo> results) {
11135            Collections.sort(results, mResolvePrioritySorter);
11136        }
11137
11138        @Override
11139        protected void dumpFilter(PrintWriter out, String prefix,
11140                PackageParser.ProviderIntentInfo filter) {
11141            out.print(prefix);
11142            out.print(
11143                    Integer.toHexString(System.identityHashCode(filter.provider)));
11144            out.print(' ');
11145            filter.provider.printComponentShortName(out);
11146            out.print(" filter ");
11147            out.println(Integer.toHexString(System.identityHashCode(filter)));
11148        }
11149
11150        @Override
11151        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11152            return filter.provider;
11153        }
11154
11155        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11156            PackageParser.Provider provider = (PackageParser.Provider)label;
11157            out.print(prefix); out.print(
11158                    Integer.toHexString(System.identityHashCode(provider)));
11159                    out.print(' ');
11160                    provider.printComponentShortName(out);
11161            if (count > 1) {
11162                out.print(" ("); out.print(count); out.print(" filters)");
11163            }
11164            out.println();
11165        }
11166
11167        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11168                = new ArrayMap<ComponentName, PackageParser.Provider>();
11169        private int mFlags;
11170    }
11171
11172    private static final class EphemeralIntentResolver
11173            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11174        @Override
11175        protected EphemeralResolveIntentInfo[] newArray(int size) {
11176            return new EphemeralResolveIntentInfo[size];
11177        }
11178
11179        @Override
11180        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11181            return true;
11182        }
11183
11184        @Override
11185        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11186                int userId) {
11187            if (!sUserManager.exists(userId)) {
11188                return null;
11189            }
11190            return info.getEphemeralResolveInfo();
11191        }
11192    }
11193
11194    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11195            new Comparator<ResolveInfo>() {
11196        public int compare(ResolveInfo r1, ResolveInfo r2) {
11197            int v1 = r1.priority;
11198            int v2 = r2.priority;
11199            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11200            if (v1 != v2) {
11201                return (v1 > v2) ? -1 : 1;
11202            }
11203            v1 = r1.preferredOrder;
11204            v2 = r2.preferredOrder;
11205            if (v1 != v2) {
11206                return (v1 > v2) ? -1 : 1;
11207            }
11208            if (r1.isDefault != r2.isDefault) {
11209                return r1.isDefault ? -1 : 1;
11210            }
11211            v1 = r1.match;
11212            v2 = r2.match;
11213            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11214            if (v1 != v2) {
11215                return (v1 > v2) ? -1 : 1;
11216            }
11217            if (r1.system != r2.system) {
11218                return r1.system ? -1 : 1;
11219            }
11220            if (r1.activityInfo != null) {
11221                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11222            }
11223            if (r1.serviceInfo != null) {
11224                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11225            }
11226            if (r1.providerInfo != null) {
11227                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11228            }
11229            return 0;
11230        }
11231    };
11232
11233    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11234            new Comparator<ProviderInfo>() {
11235        public int compare(ProviderInfo p1, ProviderInfo p2) {
11236            final int v1 = p1.initOrder;
11237            final int v2 = p2.initOrder;
11238            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11239        }
11240    };
11241
11242    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11243            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11244            final int[] userIds) {
11245        mHandler.post(new Runnable() {
11246            @Override
11247            public void run() {
11248                try {
11249                    final IActivityManager am = ActivityManagerNative.getDefault();
11250                    if (am == null) return;
11251                    final int[] resolvedUserIds;
11252                    if (userIds == null) {
11253                        resolvedUserIds = am.getRunningUserIds();
11254                    } else {
11255                        resolvedUserIds = userIds;
11256                    }
11257                    for (int id : resolvedUserIds) {
11258                        final Intent intent = new Intent(action,
11259                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11260                        if (extras != null) {
11261                            intent.putExtras(extras);
11262                        }
11263                        if (targetPkg != null) {
11264                            intent.setPackage(targetPkg);
11265                        }
11266                        // Modify the UID when posting to other users
11267                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11268                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11269                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11270                            intent.putExtra(Intent.EXTRA_UID, uid);
11271                        }
11272                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11273                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11274                        if (DEBUG_BROADCASTS) {
11275                            RuntimeException here = new RuntimeException("here");
11276                            here.fillInStackTrace();
11277                            Slog.d(TAG, "Sending to user " + id + ": "
11278                                    + intent.toShortString(false, true, false, false)
11279                                    + " " + intent.getExtras(), here);
11280                        }
11281                        am.broadcastIntent(null, intent, null, finishedReceiver,
11282                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11283                                null, finishedReceiver != null, false, id);
11284                    }
11285                } catch (RemoteException ex) {
11286                }
11287            }
11288        });
11289    }
11290
11291    /**
11292     * Check if the external storage media is available. This is true if there
11293     * is a mounted external storage medium or if the external storage is
11294     * emulated.
11295     */
11296    private boolean isExternalMediaAvailable() {
11297        return mMediaMounted || Environment.isExternalStorageEmulated();
11298    }
11299
11300    @Override
11301    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11302        // writer
11303        synchronized (mPackages) {
11304            if (!isExternalMediaAvailable()) {
11305                // If the external storage is no longer mounted at this point,
11306                // the caller may not have been able to delete all of this
11307                // packages files and can not delete any more.  Bail.
11308                return null;
11309            }
11310            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11311            if (lastPackage != null) {
11312                pkgs.remove(lastPackage);
11313            }
11314            if (pkgs.size() > 0) {
11315                return pkgs.get(0);
11316            }
11317        }
11318        return null;
11319    }
11320
11321    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11322        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11323                userId, andCode ? 1 : 0, packageName);
11324        if (mSystemReady) {
11325            msg.sendToTarget();
11326        } else {
11327            if (mPostSystemReadyMessages == null) {
11328                mPostSystemReadyMessages = new ArrayList<>();
11329            }
11330            mPostSystemReadyMessages.add(msg);
11331        }
11332    }
11333
11334    void startCleaningPackages() {
11335        // reader
11336        if (!isExternalMediaAvailable()) {
11337            return;
11338        }
11339        synchronized (mPackages) {
11340            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11341                return;
11342            }
11343        }
11344        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11345        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11346        IActivityManager am = ActivityManagerNative.getDefault();
11347        if (am != null) {
11348            try {
11349                am.startService(null, intent, null, mContext.getOpPackageName(),
11350                        UserHandle.USER_SYSTEM);
11351            } catch (RemoteException e) {
11352            }
11353        }
11354    }
11355
11356    @Override
11357    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11358            int installFlags, String installerPackageName, int userId) {
11359        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11360
11361        final int callingUid = Binder.getCallingUid();
11362        enforceCrossUserPermission(callingUid, userId,
11363                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11364
11365        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11366            try {
11367                if (observer != null) {
11368                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11369                }
11370            } catch (RemoteException re) {
11371            }
11372            return;
11373        }
11374
11375        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11376            installFlags |= PackageManager.INSTALL_FROM_ADB;
11377
11378        } else {
11379            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11380            // about installerPackageName.
11381
11382            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11383            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11384        }
11385
11386        UserHandle user;
11387        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11388            user = UserHandle.ALL;
11389        } else {
11390            user = new UserHandle(userId);
11391        }
11392
11393        // Only system components can circumvent runtime permissions when installing.
11394        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11395                && mContext.checkCallingOrSelfPermission(Manifest.permission
11396                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11397            throw new SecurityException("You need the "
11398                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11399                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11400        }
11401
11402        final File originFile = new File(originPath);
11403        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11404
11405        final Message msg = mHandler.obtainMessage(INIT_COPY);
11406        final VerificationInfo verificationInfo = new VerificationInfo(
11407                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11408        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11409                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11410                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11411                null /*certificates*/);
11412        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11413        msg.obj = params;
11414
11415        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11416                System.identityHashCode(msg.obj));
11417        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11418                System.identityHashCode(msg.obj));
11419
11420        mHandler.sendMessage(msg);
11421    }
11422
11423    void installStage(String packageName, File stagedDir, String stagedCid,
11424            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11425            String installerPackageName, int installerUid, UserHandle user,
11426            Certificate[][] certificates) {
11427        if (DEBUG_EPHEMERAL) {
11428            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11429                Slog.d(TAG, "Ephemeral install of " + packageName);
11430            }
11431        }
11432        final VerificationInfo verificationInfo = new VerificationInfo(
11433                sessionParams.originatingUri, sessionParams.referrerUri,
11434                sessionParams.originatingUid, installerUid);
11435
11436        final OriginInfo origin;
11437        if (stagedDir != null) {
11438            origin = OriginInfo.fromStagedFile(stagedDir);
11439        } else {
11440            origin = OriginInfo.fromStagedContainer(stagedCid);
11441        }
11442
11443        final Message msg = mHandler.obtainMessage(INIT_COPY);
11444        final InstallParams params = new InstallParams(origin, null, observer,
11445                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11446                verificationInfo, user, sessionParams.abiOverride,
11447                sessionParams.grantedRuntimePermissions, certificates);
11448        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11449        msg.obj = params;
11450
11451        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11452                System.identityHashCode(msg.obj));
11453        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11454                System.identityHashCode(msg.obj));
11455
11456        mHandler.sendMessage(msg);
11457    }
11458
11459    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11460            int userId) {
11461        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11462        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11463    }
11464
11465    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11466            int appId, int userId) {
11467        Bundle extras = new Bundle(1);
11468        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11469
11470        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11471                packageName, extras, 0, null, null, new int[] {userId});
11472        try {
11473            IActivityManager am = ActivityManagerNative.getDefault();
11474            if (isSystem && am.isUserRunning(userId, 0)) {
11475                // The just-installed/enabled app is bundled on the system, so presumed
11476                // to be able to run automatically without needing an explicit launch.
11477                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11478                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11479                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11480                        .setPackage(packageName);
11481                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11482                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11483            }
11484        } catch (RemoteException e) {
11485            // shouldn't happen
11486            Slog.w(TAG, "Unable to bootstrap installed package", e);
11487        }
11488    }
11489
11490    @Override
11491    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11492            int userId) {
11493        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11494        PackageSetting pkgSetting;
11495        final int uid = Binder.getCallingUid();
11496        enforceCrossUserPermission(uid, userId,
11497                true /* requireFullPermission */, true /* checkShell */,
11498                "setApplicationHiddenSetting for user " + userId);
11499
11500        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11501            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11502            return false;
11503        }
11504
11505        long callingId = Binder.clearCallingIdentity();
11506        try {
11507            boolean sendAdded = false;
11508            boolean sendRemoved = false;
11509            // writer
11510            synchronized (mPackages) {
11511                pkgSetting = mSettings.mPackages.get(packageName);
11512                if (pkgSetting == null) {
11513                    return false;
11514                }
11515                // Do not allow "android" is being disabled
11516                if ("android".equals(packageName)) {
11517                    Slog.w(TAG, "Cannot hide package: android");
11518                    return false;
11519                }
11520                // Only allow protected packages to hide themselves.
11521                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11522                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11523                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11524                    return false;
11525                }
11526
11527                if (pkgSetting.getHidden(userId) != hidden) {
11528                    pkgSetting.setHidden(hidden, userId);
11529                    mSettings.writePackageRestrictionsLPr(userId);
11530                    if (hidden) {
11531                        sendRemoved = true;
11532                    } else {
11533                        sendAdded = true;
11534                    }
11535                }
11536            }
11537            if (sendAdded) {
11538                sendPackageAddedForUser(packageName, pkgSetting, userId);
11539                return true;
11540            }
11541            if (sendRemoved) {
11542                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11543                        "hiding pkg");
11544                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11545                return true;
11546            }
11547        } finally {
11548            Binder.restoreCallingIdentity(callingId);
11549        }
11550        return false;
11551    }
11552
11553    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11554            int userId) {
11555        final PackageRemovedInfo info = new PackageRemovedInfo();
11556        info.removedPackage = packageName;
11557        info.removedUsers = new int[] {userId};
11558        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11559        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11560    }
11561
11562    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11563        if (pkgList.length > 0) {
11564            Bundle extras = new Bundle(1);
11565            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11566
11567            sendPackageBroadcast(
11568                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11569                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11570                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11571                    new int[] {userId});
11572        }
11573    }
11574
11575    /**
11576     * Returns true if application is not found or there was an error. Otherwise it returns
11577     * the hidden state of the package for the given user.
11578     */
11579    @Override
11580    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11581        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11582        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11583                true /* requireFullPermission */, false /* checkShell */,
11584                "getApplicationHidden for user " + userId);
11585        PackageSetting pkgSetting;
11586        long callingId = Binder.clearCallingIdentity();
11587        try {
11588            // writer
11589            synchronized (mPackages) {
11590                pkgSetting = mSettings.mPackages.get(packageName);
11591                if (pkgSetting == null) {
11592                    return true;
11593                }
11594                return pkgSetting.getHidden(userId);
11595            }
11596        } finally {
11597            Binder.restoreCallingIdentity(callingId);
11598        }
11599    }
11600
11601    /**
11602     * @hide
11603     */
11604    @Override
11605    public int installExistingPackageAsUser(String packageName, int userId) {
11606        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11607                null);
11608        PackageSetting pkgSetting;
11609        final int uid = Binder.getCallingUid();
11610        enforceCrossUserPermission(uid, userId,
11611                true /* requireFullPermission */, true /* checkShell */,
11612                "installExistingPackage for user " + userId);
11613        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11614            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11615        }
11616
11617        long callingId = Binder.clearCallingIdentity();
11618        try {
11619            boolean installed = false;
11620
11621            // writer
11622            synchronized (mPackages) {
11623                pkgSetting = mSettings.mPackages.get(packageName);
11624                if (pkgSetting == null) {
11625                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11626                }
11627                if (!pkgSetting.getInstalled(userId)) {
11628                    pkgSetting.setInstalled(true, userId);
11629                    pkgSetting.setHidden(false, userId);
11630                    mSettings.writePackageRestrictionsLPr(userId);
11631                    installed = true;
11632                }
11633            }
11634
11635            if (installed) {
11636                if (pkgSetting.pkg != null) {
11637                    synchronized (mInstallLock) {
11638                        // We don't need to freeze for a brand new install
11639                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11640                    }
11641                }
11642                sendPackageAddedForUser(packageName, pkgSetting, userId);
11643            }
11644        } finally {
11645            Binder.restoreCallingIdentity(callingId);
11646        }
11647
11648        return PackageManager.INSTALL_SUCCEEDED;
11649    }
11650
11651    boolean isUserRestricted(int userId, String restrictionKey) {
11652        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11653        if (restrictions.getBoolean(restrictionKey, false)) {
11654            Log.w(TAG, "User is restricted: " + restrictionKey);
11655            return true;
11656        }
11657        return false;
11658    }
11659
11660    @Override
11661    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11662            int userId) {
11663        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11664        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11665                true /* requireFullPermission */, true /* checkShell */,
11666                "setPackagesSuspended for user " + userId);
11667
11668        if (ArrayUtils.isEmpty(packageNames)) {
11669            return packageNames;
11670        }
11671
11672        // List of package names for whom the suspended state has changed.
11673        List<String> changedPackages = new ArrayList<>(packageNames.length);
11674        // List of package names for whom the suspended state is not set as requested in this
11675        // method.
11676        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11677        long callingId = Binder.clearCallingIdentity();
11678        try {
11679            for (int i = 0; i < packageNames.length; i++) {
11680                String packageName = packageNames[i];
11681                boolean changed = false;
11682                final int appId;
11683                synchronized (mPackages) {
11684                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11685                    if (pkgSetting == null) {
11686                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11687                                + "\". Skipping suspending/un-suspending.");
11688                        unactionedPackages.add(packageName);
11689                        continue;
11690                    }
11691                    appId = pkgSetting.appId;
11692                    if (pkgSetting.getSuspended(userId) != suspended) {
11693                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11694                            unactionedPackages.add(packageName);
11695                            continue;
11696                        }
11697                        pkgSetting.setSuspended(suspended, userId);
11698                        mSettings.writePackageRestrictionsLPr(userId);
11699                        changed = true;
11700                        changedPackages.add(packageName);
11701                    }
11702                }
11703
11704                if (changed && suspended) {
11705                    killApplication(packageName, UserHandle.getUid(userId, appId),
11706                            "suspending package");
11707                }
11708            }
11709        } finally {
11710            Binder.restoreCallingIdentity(callingId);
11711        }
11712
11713        if (!changedPackages.isEmpty()) {
11714            sendPackagesSuspendedForUser(changedPackages.toArray(
11715                    new String[changedPackages.size()]), userId, suspended);
11716        }
11717
11718        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11719    }
11720
11721    @Override
11722    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11723        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11724                true /* requireFullPermission */, false /* checkShell */,
11725                "isPackageSuspendedForUser for user " + userId);
11726        synchronized (mPackages) {
11727            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11728            if (pkgSetting == null) {
11729                throw new IllegalArgumentException("Unknown target package: " + packageName);
11730            }
11731            return pkgSetting.getSuspended(userId);
11732        }
11733    }
11734
11735    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11736        if (isPackageDeviceAdmin(packageName, userId)) {
11737            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11738                    + "\": has an active device admin");
11739            return false;
11740        }
11741
11742        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11743        if (packageName.equals(activeLauncherPackageName)) {
11744            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11745                    + "\": contains the active launcher");
11746            return false;
11747        }
11748
11749        if (packageName.equals(mRequiredInstallerPackage)) {
11750            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11751                    + "\": required for package installation");
11752            return false;
11753        }
11754
11755        if (packageName.equals(mRequiredVerifierPackage)) {
11756            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11757                    + "\": required for package verification");
11758            return false;
11759        }
11760
11761        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11762            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11763                    + "\": is the default dialer");
11764            return false;
11765        }
11766
11767        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11768            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11769                    + "\": protected package");
11770            return false;
11771        }
11772
11773        return true;
11774    }
11775
11776    private String getActiveLauncherPackageName(int userId) {
11777        Intent intent = new Intent(Intent.ACTION_MAIN);
11778        intent.addCategory(Intent.CATEGORY_HOME);
11779        ResolveInfo resolveInfo = resolveIntent(
11780                intent,
11781                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11782                PackageManager.MATCH_DEFAULT_ONLY,
11783                userId);
11784
11785        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11786    }
11787
11788    private String getDefaultDialerPackageName(int userId) {
11789        synchronized (mPackages) {
11790            return mSettings.getDefaultDialerPackageNameLPw(userId);
11791        }
11792    }
11793
11794    @Override
11795    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11796        mContext.enforceCallingOrSelfPermission(
11797                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11798                "Only package verification agents can verify applications");
11799
11800        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11801        final PackageVerificationResponse response = new PackageVerificationResponse(
11802                verificationCode, Binder.getCallingUid());
11803        msg.arg1 = id;
11804        msg.obj = response;
11805        mHandler.sendMessage(msg);
11806    }
11807
11808    @Override
11809    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11810            long millisecondsToDelay) {
11811        mContext.enforceCallingOrSelfPermission(
11812                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11813                "Only package verification agents can extend verification timeouts");
11814
11815        final PackageVerificationState state = mPendingVerification.get(id);
11816        final PackageVerificationResponse response = new PackageVerificationResponse(
11817                verificationCodeAtTimeout, Binder.getCallingUid());
11818
11819        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11820            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11821        }
11822        if (millisecondsToDelay < 0) {
11823            millisecondsToDelay = 0;
11824        }
11825        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11826                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11827            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11828        }
11829
11830        if ((state != null) && !state.timeoutExtended()) {
11831            state.extendTimeout();
11832
11833            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11834            msg.arg1 = id;
11835            msg.obj = response;
11836            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11837        }
11838    }
11839
11840    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11841            int verificationCode, UserHandle user) {
11842        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11843        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11844        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11845        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11846        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11847
11848        mContext.sendBroadcastAsUser(intent, user,
11849                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11850    }
11851
11852    private ComponentName matchComponentForVerifier(String packageName,
11853            List<ResolveInfo> receivers) {
11854        ActivityInfo targetReceiver = null;
11855
11856        final int NR = receivers.size();
11857        for (int i = 0; i < NR; i++) {
11858            final ResolveInfo info = receivers.get(i);
11859            if (info.activityInfo == null) {
11860                continue;
11861            }
11862
11863            if (packageName.equals(info.activityInfo.packageName)) {
11864                targetReceiver = info.activityInfo;
11865                break;
11866            }
11867        }
11868
11869        if (targetReceiver == null) {
11870            return null;
11871        }
11872
11873        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11874    }
11875
11876    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11877            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11878        if (pkgInfo.verifiers.length == 0) {
11879            return null;
11880        }
11881
11882        final int N = pkgInfo.verifiers.length;
11883        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11884        for (int i = 0; i < N; i++) {
11885            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11886
11887            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11888                    receivers);
11889            if (comp == null) {
11890                continue;
11891            }
11892
11893            final int verifierUid = getUidForVerifier(verifierInfo);
11894            if (verifierUid == -1) {
11895                continue;
11896            }
11897
11898            if (DEBUG_VERIFY) {
11899                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11900                        + " with the correct signature");
11901            }
11902            sufficientVerifiers.add(comp);
11903            verificationState.addSufficientVerifier(verifierUid);
11904        }
11905
11906        return sufficientVerifiers;
11907    }
11908
11909    private int getUidForVerifier(VerifierInfo verifierInfo) {
11910        synchronized (mPackages) {
11911            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11912            if (pkg == null) {
11913                return -1;
11914            } else if (pkg.mSignatures.length != 1) {
11915                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11916                        + " has more than one signature; ignoring");
11917                return -1;
11918            }
11919
11920            /*
11921             * If the public key of the package's signature does not match
11922             * our expected public key, then this is a different package and
11923             * we should skip.
11924             */
11925
11926            final byte[] expectedPublicKey;
11927            try {
11928                final Signature verifierSig = pkg.mSignatures[0];
11929                final PublicKey publicKey = verifierSig.getPublicKey();
11930                expectedPublicKey = publicKey.getEncoded();
11931            } catch (CertificateException e) {
11932                return -1;
11933            }
11934
11935            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11936
11937            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11938                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11939                        + " does not have the expected public key; ignoring");
11940                return -1;
11941            }
11942
11943            return pkg.applicationInfo.uid;
11944        }
11945    }
11946
11947    @Override
11948    public void finishPackageInstall(int token, boolean didLaunch) {
11949        enforceSystemOrRoot("Only the system is allowed to finish installs");
11950
11951        if (DEBUG_INSTALL) {
11952            Slog.v(TAG, "BM finishing package install for " + token);
11953        }
11954        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11955
11956        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
11957        mHandler.sendMessage(msg);
11958    }
11959
11960    /**
11961     * Get the verification agent timeout.
11962     *
11963     * @return verification timeout in milliseconds
11964     */
11965    private long getVerificationTimeout() {
11966        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11967                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11968                DEFAULT_VERIFICATION_TIMEOUT);
11969    }
11970
11971    /**
11972     * Get the default verification agent response code.
11973     *
11974     * @return default verification response code
11975     */
11976    private int getDefaultVerificationResponse() {
11977        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11978                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11979                DEFAULT_VERIFICATION_RESPONSE);
11980    }
11981
11982    /**
11983     * Check whether or not package verification has been enabled.
11984     *
11985     * @return true if verification should be performed
11986     */
11987    private boolean isVerificationEnabled(int userId, int installFlags) {
11988        if (!DEFAULT_VERIFY_ENABLE) {
11989            return false;
11990        }
11991        // Ephemeral apps don't get the full verification treatment
11992        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11993            if (DEBUG_EPHEMERAL) {
11994                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11995            }
11996            return false;
11997        }
11998
11999        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12000
12001        // Check if installing from ADB
12002        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12003            // Do not run verification in a test harness environment
12004            if (ActivityManager.isRunningInTestHarness()) {
12005                return false;
12006            }
12007            if (ensureVerifyAppsEnabled) {
12008                return true;
12009            }
12010            // Check if the developer does not want package verification for ADB installs
12011            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12012                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12013                return false;
12014            }
12015        }
12016
12017        if (ensureVerifyAppsEnabled) {
12018            return true;
12019        }
12020
12021        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12022                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12023    }
12024
12025    @Override
12026    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12027            throws RemoteException {
12028        mContext.enforceCallingOrSelfPermission(
12029                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12030                "Only intentfilter verification agents can verify applications");
12031
12032        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12033        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12034                Binder.getCallingUid(), verificationCode, failedDomains);
12035        msg.arg1 = id;
12036        msg.obj = response;
12037        mHandler.sendMessage(msg);
12038    }
12039
12040    @Override
12041    public int getIntentVerificationStatus(String packageName, int userId) {
12042        synchronized (mPackages) {
12043            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12044        }
12045    }
12046
12047    @Override
12048    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12049        mContext.enforceCallingOrSelfPermission(
12050                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12051
12052        boolean result = false;
12053        synchronized (mPackages) {
12054            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12055        }
12056        if (result) {
12057            scheduleWritePackageRestrictionsLocked(userId);
12058        }
12059        return result;
12060    }
12061
12062    @Override
12063    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12064            String packageName) {
12065        synchronized (mPackages) {
12066            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12067        }
12068    }
12069
12070    @Override
12071    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12072        if (TextUtils.isEmpty(packageName)) {
12073            return ParceledListSlice.emptyList();
12074        }
12075        synchronized (mPackages) {
12076            PackageParser.Package pkg = mPackages.get(packageName);
12077            if (pkg == null || pkg.activities == null) {
12078                return ParceledListSlice.emptyList();
12079            }
12080            final int count = pkg.activities.size();
12081            ArrayList<IntentFilter> result = new ArrayList<>();
12082            for (int n=0; n<count; n++) {
12083                PackageParser.Activity activity = pkg.activities.get(n);
12084                if (activity.intents != null && activity.intents.size() > 0) {
12085                    result.addAll(activity.intents);
12086                }
12087            }
12088            return new ParceledListSlice<>(result);
12089        }
12090    }
12091
12092    @Override
12093    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12094        mContext.enforceCallingOrSelfPermission(
12095                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12096
12097        synchronized (mPackages) {
12098            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12099            if (packageName != null) {
12100                result |= updateIntentVerificationStatus(packageName,
12101                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12102                        userId);
12103                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12104                        packageName, userId);
12105            }
12106            return result;
12107        }
12108    }
12109
12110    @Override
12111    public String getDefaultBrowserPackageName(int userId) {
12112        synchronized (mPackages) {
12113            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12114        }
12115    }
12116
12117    /**
12118     * Get the "allow unknown sources" setting.
12119     *
12120     * @return the current "allow unknown sources" setting
12121     */
12122    private int getUnknownSourcesSettings() {
12123        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12124                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12125                -1);
12126    }
12127
12128    @Override
12129    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12130        final int uid = Binder.getCallingUid();
12131        // writer
12132        synchronized (mPackages) {
12133            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12134            if (targetPackageSetting == null) {
12135                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12136            }
12137
12138            PackageSetting installerPackageSetting;
12139            if (installerPackageName != null) {
12140                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12141                if (installerPackageSetting == null) {
12142                    throw new IllegalArgumentException("Unknown installer package: "
12143                            + installerPackageName);
12144                }
12145            } else {
12146                installerPackageSetting = null;
12147            }
12148
12149            Signature[] callerSignature;
12150            Object obj = mSettings.getUserIdLPr(uid);
12151            if (obj != null) {
12152                if (obj instanceof SharedUserSetting) {
12153                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12154                } else if (obj instanceof PackageSetting) {
12155                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12156                } else {
12157                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12158                }
12159            } else {
12160                throw new SecurityException("Unknown calling UID: " + uid);
12161            }
12162
12163            // Verify: can't set installerPackageName to a package that is
12164            // not signed with the same cert as the caller.
12165            if (installerPackageSetting != null) {
12166                if (compareSignatures(callerSignature,
12167                        installerPackageSetting.signatures.mSignatures)
12168                        != PackageManager.SIGNATURE_MATCH) {
12169                    throw new SecurityException(
12170                            "Caller does not have same cert as new installer package "
12171                            + installerPackageName);
12172                }
12173            }
12174
12175            // Verify: if target already has an installer package, it must
12176            // be signed with the same cert as the caller.
12177            if (targetPackageSetting.installerPackageName != null) {
12178                PackageSetting setting = mSettings.mPackages.get(
12179                        targetPackageSetting.installerPackageName);
12180                // If the currently set package isn't valid, then it's always
12181                // okay to change it.
12182                if (setting != null) {
12183                    if (compareSignatures(callerSignature,
12184                            setting.signatures.mSignatures)
12185                            != PackageManager.SIGNATURE_MATCH) {
12186                        throw new SecurityException(
12187                                "Caller does not have same cert as old installer package "
12188                                + targetPackageSetting.installerPackageName);
12189                    }
12190                }
12191            }
12192
12193            // Okay!
12194            targetPackageSetting.installerPackageName = installerPackageName;
12195            if (installerPackageName != null) {
12196                mSettings.mInstallerPackages.add(installerPackageName);
12197            }
12198            scheduleWriteSettingsLocked();
12199        }
12200    }
12201
12202    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12203        // Queue up an async operation since the package installation may take a little while.
12204        mHandler.post(new Runnable() {
12205            public void run() {
12206                mHandler.removeCallbacks(this);
12207                 // Result object to be returned
12208                PackageInstalledInfo res = new PackageInstalledInfo();
12209                res.setReturnCode(currentStatus);
12210                res.uid = -1;
12211                res.pkg = null;
12212                res.removedInfo = null;
12213                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12214                    args.doPreInstall(res.returnCode);
12215                    synchronized (mInstallLock) {
12216                        installPackageTracedLI(args, res);
12217                    }
12218                    args.doPostInstall(res.returnCode, res.uid);
12219                }
12220
12221                // A restore should be performed at this point if (a) the install
12222                // succeeded, (b) the operation is not an update, and (c) the new
12223                // package has not opted out of backup participation.
12224                final boolean update = res.removedInfo != null
12225                        && res.removedInfo.removedPackage != null;
12226                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12227                boolean doRestore = !update
12228                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12229
12230                // Set up the post-install work request bookkeeping.  This will be used
12231                // and cleaned up by the post-install event handling regardless of whether
12232                // there's a restore pass performed.  Token values are >= 1.
12233                int token;
12234                if (mNextInstallToken < 0) mNextInstallToken = 1;
12235                token = mNextInstallToken++;
12236
12237                PostInstallData data = new PostInstallData(args, res);
12238                mRunningInstalls.put(token, data);
12239                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12240
12241                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12242                    // Pass responsibility to the Backup Manager.  It will perform a
12243                    // restore if appropriate, then pass responsibility back to the
12244                    // Package Manager to run the post-install observer callbacks
12245                    // and broadcasts.
12246                    IBackupManager bm = IBackupManager.Stub.asInterface(
12247                            ServiceManager.getService(Context.BACKUP_SERVICE));
12248                    if (bm != null) {
12249                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12250                                + " to BM for possible restore");
12251                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12252                        try {
12253                            // TODO: http://b/22388012
12254                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12255                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12256                            } else {
12257                                doRestore = false;
12258                            }
12259                        } catch (RemoteException e) {
12260                            // can't happen; the backup manager is local
12261                        } catch (Exception e) {
12262                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12263                            doRestore = false;
12264                        }
12265                    } else {
12266                        Slog.e(TAG, "Backup Manager not found!");
12267                        doRestore = false;
12268                    }
12269                }
12270
12271                if (!doRestore) {
12272                    // No restore possible, or the Backup Manager was mysteriously not
12273                    // available -- just fire the post-install work request directly.
12274                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12275
12276                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12277
12278                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12279                    mHandler.sendMessage(msg);
12280                }
12281            }
12282        });
12283    }
12284
12285    /**
12286     * Callback from PackageSettings whenever an app is first transitioned out of the
12287     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12288     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12289     * here whether the app is the target of an ongoing install, and only send the
12290     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12291     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12292     * handling.
12293     */
12294    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12295        // Serialize this with the rest of the install-process message chain.  In the
12296        // restore-at-install case, this Runnable will necessarily run before the
12297        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12298        // are coherent.  In the non-restore case, the app has already completed install
12299        // and been launched through some other means, so it is not in a problematic
12300        // state for observers to see the FIRST_LAUNCH signal.
12301        mHandler.post(new Runnable() {
12302            @Override
12303            public void run() {
12304                for (int i = 0; i < mRunningInstalls.size(); i++) {
12305                    final PostInstallData data = mRunningInstalls.valueAt(i);
12306                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12307                        continue;
12308                    }
12309                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12310                        // right package; but is it for the right user?
12311                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12312                            if (userId == data.res.newUsers[uIndex]) {
12313                                if (DEBUG_BACKUP) {
12314                                    Slog.i(TAG, "Package " + pkgName
12315                                            + " being restored so deferring FIRST_LAUNCH");
12316                                }
12317                                return;
12318                            }
12319                        }
12320                    }
12321                }
12322                // didn't find it, so not being restored
12323                if (DEBUG_BACKUP) {
12324                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12325                }
12326                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12327            }
12328        });
12329    }
12330
12331    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12332        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12333                installerPkg, null, userIds);
12334    }
12335
12336    private abstract class HandlerParams {
12337        private static final int MAX_RETRIES = 4;
12338
12339        /**
12340         * Number of times startCopy() has been attempted and had a non-fatal
12341         * error.
12342         */
12343        private int mRetries = 0;
12344
12345        /** User handle for the user requesting the information or installation. */
12346        private final UserHandle mUser;
12347        String traceMethod;
12348        int traceCookie;
12349
12350        HandlerParams(UserHandle user) {
12351            mUser = user;
12352        }
12353
12354        UserHandle getUser() {
12355            return mUser;
12356        }
12357
12358        HandlerParams setTraceMethod(String traceMethod) {
12359            this.traceMethod = traceMethod;
12360            return this;
12361        }
12362
12363        HandlerParams setTraceCookie(int traceCookie) {
12364            this.traceCookie = traceCookie;
12365            return this;
12366        }
12367
12368        final boolean startCopy() {
12369            boolean res;
12370            try {
12371                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12372
12373                if (++mRetries > MAX_RETRIES) {
12374                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12375                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12376                    handleServiceError();
12377                    return false;
12378                } else {
12379                    handleStartCopy();
12380                    res = true;
12381                }
12382            } catch (RemoteException e) {
12383                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12384                mHandler.sendEmptyMessage(MCS_RECONNECT);
12385                res = false;
12386            }
12387            handleReturnCode();
12388            return res;
12389        }
12390
12391        final void serviceError() {
12392            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12393            handleServiceError();
12394            handleReturnCode();
12395        }
12396
12397        abstract void handleStartCopy() throws RemoteException;
12398        abstract void handleServiceError();
12399        abstract void handleReturnCode();
12400    }
12401
12402    class MeasureParams extends HandlerParams {
12403        private final PackageStats mStats;
12404        private boolean mSuccess;
12405
12406        private final IPackageStatsObserver mObserver;
12407
12408        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12409            super(new UserHandle(stats.userHandle));
12410            mObserver = observer;
12411            mStats = stats;
12412        }
12413
12414        @Override
12415        public String toString() {
12416            return "MeasureParams{"
12417                + Integer.toHexString(System.identityHashCode(this))
12418                + " " + mStats.packageName + "}";
12419        }
12420
12421        @Override
12422        void handleStartCopy() throws RemoteException {
12423            synchronized (mInstallLock) {
12424                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12425            }
12426
12427            if (mSuccess) {
12428                boolean mounted = false;
12429                try {
12430                    final String status = Environment.getExternalStorageState();
12431                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12432                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12433                } catch (Exception e) {
12434                }
12435
12436                if (mounted) {
12437                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12438
12439                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12440                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12441
12442                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12443                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12444
12445                    // Always subtract cache size, since it's a subdirectory
12446                    mStats.externalDataSize -= mStats.externalCacheSize;
12447
12448                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12449                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12450
12451                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12452                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12453                }
12454            }
12455        }
12456
12457        @Override
12458        void handleReturnCode() {
12459            if (mObserver != null) {
12460                try {
12461                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12462                } catch (RemoteException e) {
12463                    Slog.i(TAG, "Observer no longer exists.");
12464                }
12465            }
12466        }
12467
12468        @Override
12469        void handleServiceError() {
12470            Slog.e(TAG, "Could not measure application " + mStats.packageName
12471                            + " external storage");
12472        }
12473    }
12474
12475    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12476            throws RemoteException {
12477        long result = 0;
12478        for (File path : paths) {
12479            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12480        }
12481        return result;
12482    }
12483
12484    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12485        for (File path : paths) {
12486            try {
12487                mcs.clearDirectory(path.getAbsolutePath());
12488            } catch (RemoteException e) {
12489            }
12490        }
12491    }
12492
12493    static class OriginInfo {
12494        /**
12495         * Location where install is coming from, before it has been
12496         * copied/renamed into place. This could be a single monolithic APK
12497         * file, or a cluster directory. This location may be untrusted.
12498         */
12499        final File file;
12500        final String cid;
12501
12502        /**
12503         * Flag indicating that {@link #file} or {@link #cid} has already been
12504         * staged, meaning downstream users don't need to defensively copy the
12505         * contents.
12506         */
12507        final boolean staged;
12508
12509        /**
12510         * Flag indicating that {@link #file} or {@link #cid} is an already
12511         * installed app that is being moved.
12512         */
12513        final boolean existing;
12514
12515        final String resolvedPath;
12516        final File resolvedFile;
12517
12518        static OriginInfo fromNothing() {
12519            return new OriginInfo(null, null, false, false);
12520        }
12521
12522        static OriginInfo fromUntrustedFile(File file) {
12523            return new OriginInfo(file, null, false, false);
12524        }
12525
12526        static OriginInfo fromExistingFile(File file) {
12527            return new OriginInfo(file, null, false, true);
12528        }
12529
12530        static OriginInfo fromStagedFile(File file) {
12531            return new OriginInfo(file, null, true, false);
12532        }
12533
12534        static OriginInfo fromStagedContainer(String cid) {
12535            return new OriginInfo(null, cid, true, false);
12536        }
12537
12538        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12539            this.file = file;
12540            this.cid = cid;
12541            this.staged = staged;
12542            this.existing = existing;
12543
12544            if (cid != null) {
12545                resolvedPath = PackageHelper.getSdDir(cid);
12546                resolvedFile = new File(resolvedPath);
12547            } else if (file != null) {
12548                resolvedPath = file.getAbsolutePath();
12549                resolvedFile = file;
12550            } else {
12551                resolvedPath = null;
12552                resolvedFile = null;
12553            }
12554        }
12555    }
12556
12557    static class MoveInfo {
12558        final int moveId;
12559        final String fromUuid;
12560        final String toUuid;
12561        final String packageName;
12562        final String dataAppName;
12563        final int appId;
12564        final String seinfo;
12565        final int targetSdkVersion;
12566
12567        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12568                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12569            this.moveId = moveId;
12570            this.fromUuid = fromUuid;
12571            this.toUuid = toUuid;
12572            this.packageName = packageName;
12573            this.dataAppName = dataAppName;
12574            this.appId = appId;
12575            this.seinfo = seinfo;
12576            this.targetSdkVersion = targetSdkVersion;
12577        }
12578    }
12579
12580    static class VerificationInfo {
12581        /** A constant used to indicate that a uid value is not present. */
12582        public static final int NO_UID = -1;
12583
12584        /** URI referencing where the package was downloaded from. */
12585        final Uri originatingUri;
12586
12587        /** HTTP referrer URI associated with the originatingURI. */
12588        final Uri referrer;
12589
12590        /** UID of the application that the install request originated from. */
12591        final int originatingUid;
12592
12593        /** UID of application requesting the install */
12594        final int installerUid;
12595
12596        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12597            this.originatingUri = originatingUri;
12598            this.referrer = referrer;
12599            this.originatingUid = originatingUid;
12600            this.installerUid = installerUid;
12601        }
12602    }
12603
12604    class InstallParams extends HandlerParams {
12605        final OriginInfo origin;
12606        final MoveInfo move;
12607        final IPackageInstallObserver2 observer;
12608        int installFlags;
12609        final String installerPackageName;
12610        final String volumeUuid;
12611        private InstallArgs mArgs;
12612        private int mRet;
12613        final String packageAbiOverride;
12614        final String[] grantedRuntimePermissions;
12615        final VerificationInfo verificationInfo;
12616        final Certificate[][] certificates;
12617
12618        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12619                int installFlags, String installerPackageName, String volumeUuid,
12620                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12621                String[] grantedPermissions, Certificate[][] certificates) {
12622            super(user);
12623            this.origin = origin;
12624            this.move = move;
12625            this.observer = observer;
12626            this.installFlags = installFlags;
12627            this.installerPackageName = installerPackageName;
12628            this.volumeUuid = volumeUuid;
12629            this.verificationInfo = verificationInfo;
12630            this.packageAbiOverride = packageAbiOverride;
12631            this.grantedRuntimePermissions = grantedPermissions;
12632            this.certificates = certificates;
12633        }
12634
12635        @Override
12636        public String toString() {
12637            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12638                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12639        }
12640
12641        private int installLocationPolicy(PackageInfoLite pkgLite) {
12642            String packageName = pkgLite.packageName;
12643            int installLocation = pkgLite.installLocation;
12644            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12645            // reader
12646            synchronized (mPackages) {
12647                // Currently installed package which the new package is attempting to replace or
12648                // null if no such package is installed.
12649                PackageParser.Package installedPkg = mPackages.get(packageName);
12650                // Package which currently owns the data which the new package will own if installed.
12651                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12652                // will be null whereas dataOwnerPkg will contain information about the package
12653                // which was uninstalled while keeping its data.
12654                PackageParser.Package dataOwnerPkg = installedPkg;
12655                if (dataOwnerPkg  == null) {
12656                    PackageSetting ps = mSettings.mPackages.get(packageName);
12657                    if (ps != null) {
12658                        dataOwnerPkg = ps.pkg;
12659                    }
12660                }
12661
12662                if (dataOwnerPkg != null) {
12663                    // If installed, the package will get access to data left on the device by its
12664                    // predecessor. As a security measure, this is permited only if this is not a
12665                    // version downgrade or if the predecessor package is marked as debuggable and
12666                    // a downgrade is explicitly requested.
12667                    //
12668                    // On debuggable platform builds, downgrades are permitted even for
12669                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12670                    // not offer security guarantees and thus it's OK to disable some security
12671                    // mechanisms to make debugging/testing easier on those builds. However, even on
12672                    // debuggable builds downgrades of packages are permitted only if requested via
12673                    // installFlags. This is because we aim to keep the behavior of debuggable
12674                    // platform builds as close as possible to the behavior of non-debuggable
12675                    // platform builds.
12676                    final boolean downgradeRequested =
12677                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12678                    final boolean packageDebuggable =
12679                                (dataOwnerPkg.applicationInfo.flags
12680                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12681                    final boolean downgradePermitted =
12682                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12683                    if (!downgradePermitted) {
12684                        try {
12685                            checkDowngrade(dataOwnerPkg, pkgLite);
12686                        } catch (PackageManagerException e) {
12687                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12688                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12689                        }
12690                    }
12691                }
12692
12693                if (installedPkg != null) {
12694                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12695                        // Check for updated system application.
12696                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12697                            if (onSd) {
12698                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12699                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12700                            }
12701                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12702                        } else {
12703                            if (onSd) {
12704                                // Install flag overrides everything.
12705                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12706                            }
12707                            // If current upgrade specifies particular preference
12708                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12709                                // Application explicitly specified internal.
12710                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12711                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12712                                // App explictly prefers external. Let policy decide
12713                            } else {
12714                                // Prefer previous location
12715                                if (isExternal(installedPkg)) {
12716                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12717                                }
12718                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12719                            }
12720                        }
12721                    } else {
12722                        // Invalid install. Return error code
12723                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12724                    }
12725                }
12726            }
12727            // All the special cases have been taken care of.
12728            // Return result based on recommended install location.
12729            if (onSd) {
12730                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12731            }
12732            return pkgLite.recommendedInstallLocation;
12733        }
12734
12735        /*
12736         * Invoke remote method to get package information and install
12737         * location values. Override install location based on default
12738         * policy if needed and then create install arguments based
12739         * on the install location.
12740         */
12741        public void handleStartCopy() throws RemoteException {
12742            int ret = PackageManager.INSTALL_SUCCEEDED;
12743
12744            // If we're already staged, we've firmly committed to an install location
12745            if (origin.staged) {
12746                if (origin.file != null) {
12747                    installFlags |= PackageManager.INSTALL_INTERNAL;
12748                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12749                } else if (origin.cid != null) {
12750                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12751                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12752                } else {
12753                    throw new IllegalStateException("Invalid stage location");
12754                }
12755            }
12756
12757            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12758            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12759            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12760            PackageInfoLite pkgLite = null;
12761
12762            if (onInt && onSd) {
12763                // Check if both bits are set.
12764                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12765                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12766            } else if (onSd && ephemeral) {
12767                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12768                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12769            } else {
12770                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12771                        packageAbiOverride);
12772
12773                if (DEBUG_EPHEMERAL && ephemeral) {
12774                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12775                }
12776
12777                /*
12778                 * If we have too little free space, try to free cache
12779                 * before giving up.
12780                 */
12781                if (!origin.staged && pkgLite.recommendedInstallLocation
12782                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12783                    // TODO: focus freeing disk space on the target device
12784                    final StorageManager storage = StorageManager.from(mContext);
12785                    final long lowThreshold = storage.getStorageLowBytes(
12786                            Environment.getDataDirectory());
12787
12788                    final long sizeBytes = mContainerService.calculateInstalledSize(
12789                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12790
12791                    try {
12792                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12793                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12794                                installFlags, packageAbiOverride);
12795                    } catch (InstallerException e) {
12796                        Slog.w(TAG, "Failed to free cache", e);
12797                    }
12798
12799                    /*
12800                     * The cache free must have deleted the file we
12801                     * downloaded to install.
12802                     *
12803                     * TODO: fix the "freeCache" call to not delete
12804                     *       the file we care about.
12805                     */
12806                    if (pkgLite.recommendedInstallLocation
12807                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12808                        pkgLite.recommendedInstallLocation
12809                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12810                    }
12811                }
12812            }
12813
12814            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12815                int loc = pkgLite.recommendedInstallLocation;
12816                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12817                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12818                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12819                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12820                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12821                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12822                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12823                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12824                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12825                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12826                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12827                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12828                } else {
12829                    // Override with defaults if needed.
12830                    loc = installLocationPolicy(pkgLite);
12831                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12832                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12833                    } else if (!onSd && !onInt) {
12834                        // Override install location with flags
12835                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12836                            // Set the flag to install on external media.
12837                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12838                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12839                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12840                            if (DEBUG_EPHEMERAL) {
12841                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12842                            }
12843                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12844                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12845                                    |PackageManager.INSTALL_INTERNAL);
12846                        } else {
12847                            // Make sure the flag for installing on external
12848                            // media is unset
12849                            installFlags |= PackageManager.INSTALL_INTERNAL;
12850                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12851                        }
12852                    }
12853                }
12854            }
12855
12856            final InstallArgs args = createInstallArgs(this);
12857            mArgs = args;
12858
12859            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12860                // TODO: http://b/22976637
12861                // Apps installed for "all" users use the device owner to verify the app
12862                UserHandle verifierUser = getUser();
12863                if (verifierUser == UserHandle.ALL) {
12864                    verifierUser = UserHandle.SYSTEM;
12865                }
12866
12867                /*
12868                 * Determine if we have any installed package verifiers. If we
12869                 * do, then we'll defer to them to verify the packages.
12870                 */
12871                final int requiredUid = mRequiredVerifierPackage == null ? -1
12872                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12873                                verifierUser.getIdentifier());
12874                if (!origin.existing && requiredUid != -1
12875                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12876                    final Intent verification = new Intent(
12877                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12878                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12879                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12880                            PACKAGE_MIME_TYPE);
12881                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12882
12883                    // Query all live verifiers based on current user state
12884                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12885                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12886
12887                    if (DEBUG_VERIFY) {
12888                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12889                                + verification.toString() + " with " + pkgLite.verifiers.length
12890                                + " optional verifiers");
12891                    }
12892
12893                    final int verificationId = mPendingVerificationToken++;
12894
12895                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12896
12897                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12898                            installerPackageName);
12899
12900                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12901                            installFlags);
12902
12903                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12904                            pkgLite.packageName);
12905
12906                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12907                            pkgLite.versionCode);
12908
12909                    if (verificationInfo != null) {
12910                        if (verificationInfo.originatingUri != null) {
12911                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12912                                    verificationInfo.originatingUri);
12913                        }
12914                        if (verificationInfo.referrer != null) {
12915                            verification.putExtra(Intent.EXTRA_REFERRER,
12916                                    verificationInfo.referrer);
12917                        }
12918                        if (verificationInfo.originatingUid >= 0) {
12919                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12920                                    verificationInfo.originatingUid);
12921                        }
12922                        if (verificationInfo.installerUid >= 0) {
12923                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12924                                    verificationInfo.installerUid);
12925                        }
12926                    }
12927
12928                    final PackageVerificationState verificationState = new PackageVerificationState(
12929                            requiredUid, args);
12930
12931                    mPendingVerification.append(verificationId, verificationState);
12932
12933                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12934                            receivers, verificationState);
12935
12936                    /*
12937                     * If any sufficient verifiers were listed in the package
12938                     * manifest, attempt to ask them.
12939                     */
12940                    if (sufficientVerifiers != null) {
12941                        final int N = sufficientVerifiers.size();
12942                        if (N == 0) {
12943                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12944                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12945                        } else {
12946                            for (int i = 0; i < N; i++) {
12947                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12948
12949                                final Intent sufficientIntent = new Intent(verification);
12950                                sufficientIntent.setComponent(verifierComponent);
12951                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12952                            }
12953                        }
12954                    }
12955
12956                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12957                            mRequiredVerifierPackage, receivers);
12958                    if (ret == PackageManager.INSTALL_SUCCEEDED
12959                            && mRequiredVerifierPackage != null) {
12960                        Trace.asyncTraceBegin(
12961                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12962                        /*
12963                         * Send the intent to the required verification agent,
12964                         * but only start the verification timeout after the
12965                         * target BroadcastReceivers have run.
12966                         */
12967                        verification.setComponent(requiredVerifierComponent);
12968                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12969                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12970                                new BroadcastReceiver() {
12971                                    @Override
12972                                    public void onReceive(Context context, Intent intent) {
12973                                        final Message msg = mHandler
12974                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12975                                        msg.arg1 = verificationId;
12976                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12977                                    }
12978                                }, null, 0, null, null);
12979
12980                        /*
12981                         * We don't want the copy to proceed until verification
12982                         * succeeds, so null out this field.
12983                         */
12984                        mArgs = null;
12985                    }
12986                } else {
12987                    /*
12988                     * No package verification is enabled, so immediately start
12989                     * the remote call to initiate copy using temporary file.
12990                     */
12991                    ret = args.copyApk(mContainerService, true);
12992                }
12993            }
12994
12995            mRet = ret;
12996        }
12997
12998        @Override
12999        void handleReturnCode() {
13000            // If mArgs is null, then MCS couldn't be reached. When it
13001            // reconnects, it will try again to install. At that point, this
13002            // will succeed.
13003            if (mArgs != null) {
13004                processPendingInstall(mArgs, mRet);
13005            }
13006        }
13007
13008        @Override
13009        void handleServiceError() {
13010            mArgs = createInstallArgs(this);
13011            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13012        }
13013
13014        public boolean isForwardLocked() {
13015            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13016        }
13017    }
13018
13019    /**
13020     * Used during creation of InstallArgs
13021     *
13022     * @param installFlags package installation flags
13023     * @return true if should be installed on external storage
13024     */
13025    private static boolean installOnExternalAsec(int installFlags) {
13026        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13027            return false;
13028        }
13029        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13030            return true;
13031        }
13032        return false;
13033    }
13034
13035    /**
13036     * Used during creation of InstallArgs
13037     *
13038     * @param installFlags package installation flags
13039     * @return true if should be installed as forward locked
13040     */
13041    private static boolean installForwardLocked(int installFlags) {
13042        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13043    }
13044
13045    private InstallArgs createInstallArgs(InstallParams params) {
13046        if (params.move != null) {
13047            return new MoveInstallArgs(params);
13048        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13049            return new AsecInstallArgs(params);
13050        } else {
13051            return new FileInstallArgs(params);
13052        }
13053    }
13054
13055    /**
13056     * Create args that describe an existing installed package. Typically used
13057     * when cleaning up old installs, or used as a move source.
13058     */
13059    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13060            String resourcePath, String[] instructionSets) {
13061        final boolean isInAsec;
13062        if (installOnExternalAsec(installFlags)) {
13063            /* Apps on SD card are always in ASEC containers. */
13064            isInAsec = true;
13065        } else if (installForwardLocked(installFlags)
13066                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13067            /*
13068             * Forward-locked apps are only in ASEC containers if they're the
13069             * new style
13070             */
13071            isInAsec = true;
13072        } else {
13073            isInAsec = false;
13074        }
13075
13076        if (isInAsec) {
13077            return new AsecInstallArgs(codePath, instructionSets,
13078                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13079        } else {
13080            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13081        }
13082    }
13083
13084    static abstract class InstallArgs {
13085        /** @see InstallParams#origin */
13086        final OriginInfo origin;
13087        /** @see InstallParams#move */
13088        final MoveInfo move;
13089
13090        final IPackageInstallObserver2 observer;
13091        // Always refers to PackageManager flags only
13092        final int installFlags;
13093        final String installerPackageName;
13094        final String volumeUuid;
13095        final UserHandle user;
13096        final String abiOverride;
13097        final String[] installGrantPermissions;
13098        /** If non-null, drop an async trace when the install completes */
13099        final String traceMethod;
13100        final int traceCookie;
13101        final Certificate[][] certificates;
13102
13103        // The list of instruction sets supported by this app. This is currently
13104        // only used during the rmdex() phase to clean up resources. We can get rid of this
13105        // if we move dex files under the common app path.
13106        /* nullable */ String[] instructionSets;
13107
13108        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13109                int installFlags, String installerPackageName, String volumeUuid,
13110                UserHandle user, String[] instructionSets,
13111                String abiOverride, String[] installGrantPermissions,
13112                String traceMethod, int traceCookie, Certificate[][] certificates) {
13113            this.origin = origin;
13114            this.move = move;
13115            this.installFlags = installFlags;
13116            this.observer = observer;
13117            this.installerPackageName = installerPackageName;
13118            this.volumeUuid = volumeUuid;
13119            this.user = user;
13120            this.instructionSets = instructionSets;
13121            this.abiOverride = abiOverride;
13122            this.installGrantPermissions = installGrantPermissions;
13123            this.traceMethod = traceMethod;
13124            this.traceCookie = traceCookie;
13125            this.certificates = certificates;
13126        }
13127
13128        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13129        abstract int doPreInstall(int status);
13130
13131        /**
13132         * Rename package into final resting place. All paths on the given
13133         * scanned package should be updated to reflect the rename.
13134         */
13135        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13136        abstract int doPostInstall(int status, int uid);
13137
13138        /** @see PackageSettingBase#codePathString */
13139        abstract String getCodePath();
13140        /** @see PackageSettingBase#resourcePathString */
13141        abstract String getResourcePath();
13142
13143        // Need installer lock especially for dex file removal.
13144        abstract void cleanUpResourcesLI();
13145        abstract boolean doPostDeleteLI(boolean delete);
13146
13147        /**
13148         * Called before the source arguments are copied. This is used mostly
13149         * for MoveParams when it needs to read the source file to put it in the
13150         * destination.
13151         */
13152        int doPreCopy() {
13153            return PackageManager.INSTALL_SUCCEEDED;
13154        }
13155
13156        /**
13157         * Called after the source arguments are copied. This is used mostly for
13158         * MoveParams when it needs to read the source file to put it in the
13159         * destination.
13160         */
13161        int doPostCopy(int uid) {
13162            return PackageManager.INSTALL_SUCCEEDED;
13163        }
13164
13165        protected boolean isFwdLocked() {
13166            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13167        }
13168
13169        protected boolean isExternalAsec() {
13170            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13171        }
13172
13173        protected boolean isEphemeral() {
13174            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13175        }
13176
13177        UserHandle getUser() {
13178            return user;
13179        }
13180    }
13181
13182    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13183        if (!allCodePaths.isEmpty()) {
13184            if (instructionSets == null) {
13185                throw new IllegalStateException("instructionSet == null");
13186            }
13187            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13188            for (String codePath : allCodePaths) {
13189                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13190                    try {
13191                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13192                    } catch (InstallerException ignored) {
13193                    }
13194                }
13195            }
13196        }
13197    }
13198
13199    /**
13200     * Logic to handle installation of non-ASEC applications, including copying
13201     * and renaming logic.
13202     */
13203    class FileInstallArgs extends InstallArgs {
13204        private File codeFile;
13205        private File resourceFile;
13206
13207        // Example topology:
13208        // /data/app/com.example/base.apk
13209        // /data/app/com.example/split_foo.apk
13210        // /data/app/com.example/lib/arm/libfoo.so
13211        // /data/app/com.example/lib/arm64/libfoo.so
13212        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13213
13214        /** New install */
13215        FileInstallArgs(InstallParams params) {
13216            super(params.origin, params.move, params.observer, params.installFlags,
13217                    params.installerPackageName, params.volumeUuid,
13218                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13219                    params.grantedRuntimePermissions,
13220                    params.traceMethod, params.traceCookie, params.certificates);
13221            if (isFwdLocked()) {
13222                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13223            }
13224        }
13225
13226        /** Existing install */
13227        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13228            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13229                    null, null, null, 0, null /*certificates*/);
13230            this.codeFile = (codePath != null) ? new File(codePath) : null;
13231            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13232        }
13233
13234        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13235            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13236            try {
13237                return doCopyApk(imcs, temp);
13238            } finally {
13239                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13240            }
13241        }
13242
13243        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13244            if (origin.staged) {
13245                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13246                codeFile = origin.file;
13247                resourceFile = origin.file;
13248                return PackageManager.INSTALL_SUCCEEDED;
13249            }
13250
13251            try {
13252                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13253                final File tempDir =
13254                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13255                codeFile = tempDir;
13256                resourceFile = tempDir;
13257            } catch (IOException e) {
13258                Slog.w(TAG, "Failed to create copy file: " + e);
13259                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13260            }
13261
13262            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13263                @Override
13264                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13265                    if (!FileUtils.isValidExtFilename(name)) {
13266                        throw new IllegalArgumentException("Invalid filename: " + name);
13267                    }
13268                    try {
13269                        final File file = new File(codeFile, name);
13270                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13271                                O_RDWR | O_CREAT, 0644);
13272                        Os.chmod(file.getAbsolutePath(), 0644);
13273                        return new ParcelFileDescriptor(fd);
13274                    } catch (ErrnoException e) {
13275                        throw new RemoteException("Failed to open: " + e.getMessage());
13276                    }
13277                }
13278            };
13279
13280            int ret = PackageManager.INSTALL_SUCCEEDED;
13281            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13282            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13283                Slog.e(TAG, "Failed to copy package");
13284                return ret;
13285            }
13286
13287            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13288            NativeLibraryHelper.Handle handle = null;
13289            try {
13290                handle = NativeLibraryHelper.Handle.create(codeFile);
13291                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13292                        abiOverride);
13293            } catch (IOException e) {
13294                Slog.e(TAG, "Copying native libraries failed", e);
13295                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13296            } finally {
13297                IoUtils.closeQuietly(handle);
13298            }
13299
13300            return ret;
13301        }
13302
13303        int doPreInstall(int status) {
13304            if (status != PackageManager.INSTALL_SUCCEEDED) {
13305                cleanUp();
13306            }
13307            return status;
13308        }
13309
13310        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13311            if (status != PackageManager.INSTALL_SUCCEEDED) {
13312                cleanUp();
13313                return false;
13314            }
13315
13316            final File targetDir = codeFile.getParentFile();
13317            final File beforeCodeFile = codeFile;
13318            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13319
13320            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13321            try {
13322                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13323            } catch (ErrnoException e) {
13324                Slog.w(TAG, "Failed to rename", e);
13325                return false;
13326            }
13327
13328            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13329                Slog.w(TAG, "Failed to restorecon");
13330                return false;
13331            }
13332
13333            // Reflect the rename internally
13334            codeFile = afterCodeFile;
13335            resourceFile = afterCodeFile;
13336
13337            // Reflect the rename in scanned details
13338            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13339            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13340                    afterCodeFile, pkg.baseCodePath));
13341            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13342                    afterCodeFile, pkg.splitCodePaths));
13343
13344            // Reflect the rename in app info
13345            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13346            pkg.setApplicationInfoCodePath(pkg.codePath);
13347            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13348            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13349            pkg.setApplicationInfoResourcePath(pkg.codePath);
13350            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13351            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13352
13353            return true;
13354        }
13355
13356        int doPostInstall(int status, int uid) {
13357            if (status != PackageManager.INSTALL_SUCCEEDED) {
13358                cleanUp();
13359            }
13360            return status;
13361        }
13362
13363        @Override
13364        String getCodePath() {
13365            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13366        }
13367
13368        @Override
13369        String getResourcePath() {
13370            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13371        }
13372
13373        private boolean cleanUp() {
13374            if (codeFile == null || !codeFile.exists()) {
13375                return false;
13376            }
13377
13378            removeCodePathLI(codeFile);
13379
13380            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13381                resourceFile.delete();
13382            }
13383
13384            return true;
13385        }
13386
13387        void cleanUpResourcesLI() {
13388            // Try enumerating all code paths before deleting
13389            List<String> allCodePaths = Collections.EMPTY_LIST;
13390            if (codeFile != null && codeFile.exists()) {
13391                try {
13392                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13393                    allCodePaths = pkg.getAllCodePaths();
13394                } catch (PackageParserException e) {
13395                    // Ignored; we tried our best
13396                }
13397            }
13398
13399            cleanUp();
13400            removeDexFiles(allCodePaths, instructionSets);
13401        }
13402
13403        boolean doPostDeleteLI(boolean delete) {
13404            // XXX err, shouldn't we respect the delete flag?
13405            cleanUpResourcesLI();
13406            return true;
13407        }
13408    }
13409
13410    private boolean isAsecExternal(String cid) {
13411        final String asecPath = PackageHelper.getSdFilesystem(cid);
13412        return !asecPath.startsWith(mAsecInternalPath);
13413    }
13414
13415    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13416            PackageManagerException {
13417        if (copyRet < 0) {
13418            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13419                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13420                throw new PackageManagerException(copyRet, message);
13421            }
13422        }
13423    }
13424
13425    /**
13426     * Extract the MountService "container ID" from the full code path of an
13427     * .apk.
13428     */
13429    static String cidFromCodePath(String fullCodePath) {
13430        int eidx = fullCodePath.lastIndexOf("/");
13431        String subStr1 = fullCodePath.substring(0, eidx);
13432        int sidx = subStr1.lastIndexOf("/");
13433        return subStr1.substring(sidx+1, eidx);
13434    }
13435
13436    /**
13437     * Logic to handle installation of ASEC applications, including copying and
13438     * renaming logic.
13439     */
13440    class AsecInstallArgs extends InstallArgs {
13441        static final String RES_FILE_NAME = "pkg.apk";
13442        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13443
13444        String cid;
13445        String packagePath;
13446        String resourcePath;
13447
13448        /** New install */
13449        AsecInstallArgs(InstallParams params) {
13450            super(params.origin, params.move, params.observer, params.installFlags,
13451                    params.installerPackageName, params.volumeUuid,
13452                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13453                    params.grantedRuntimePermissions,
13454                    params.traceMethod, params.traceCookie, params.certificates);
13455        }
13456
13457        /** Existing install */
13458        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13459                        boolean isExternal, boolean isForwardLocked) {
13460            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13461              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13462                    instructionSets, null, null, null, 0, null /*certificates*/);
13463            // Hackily pretend we're still looking at a full code path
13464            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13465                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13466            }
13467
13468            // Extract cid from fullCodePath
13469            int eidx = fullCodePath.lastIndexOf("/");
13470            String subStr1 = fullCodePath.substring(0, eidx);
13471            int sidx = subStr1.lastIndexOf("/");
13472            cid = subStr1.substring(sidx+1, eidx);
13473            setMountPath(subStr1);
13474        }
13475
13476        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13477            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13478              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13479                    instructionSets, null, null, null, 0, null /*certificates*/);
13480            this.cid = cid;
13481            setMountPath(PackageHelper.getSdDir(cid));
13482        }
13483
13484        void createCopyFile() {
13485            cid = mInstallerService.allocateExternalStageCidLegacy();
13486        }
13487
13488        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13489            if (origin.staged && origin.cid != null) {
13490                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13491                cid = origin.cid;
13492                setMountPath(PackageHelper.getSdDir(cid));
13493                return PackageManager.INSTALL_SUCCEEDED;
13494            }
13495
13496            if (temp) {
13497                createCopyFile();
13498            } else {
13499                /*
13500                 * Pre-emptively destroy the container since it's destroyed if
13501                 * copying fails due to it existing anyway.
13502                 */
13503                PackageHelper.destroySdDir(cid);
13504            }
13505
13506            final String newMountPath = imcs.copyPackageToContainer(
13507                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13508                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13509
13510            if (newMountPath != null) {
13511                setMountPath(newMountPath);
13512                return PackageManager.INSTALL_SUCCEEDED;
13513            } else {
13514                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13515            }
13516        }
13517
13518        @Override
13519        String getCodePath() {
13520            return packagePath;
13521        }
13522
13523        @Override
13524        String getResourcePath() {
13525            return resourcePath;
13526        }
13527
13528        int doPreInstall(int status) {
13529            if (status != PackageManager.INSTALL_SUCCEEDED) {
13530                // Destroy container
13531                PackageHelper.destroySdDir(cid);
13532            } else {
13533                boolean mounted = PackageHelper.isContainerMounted(cid);
13534                if (!mounted) {
13535                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13536                            Process.SYSTEM_UID);
13537                    if (newMountPath != null) {
13538                        setMountPath(newMountPath);
13539                    } else {
13540                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13541                    }
13542                }
13543            }
13544            return status;
13545        }
13546
13547        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13548            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13549            String newMountPath = null;
13550            if (PackageHelper.isContainerMounted(cid)) {
13551                // Unmount the container
13552                if (!PackageHelper.unMountSdDir(cid)) {
13553                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13554                    return false;
13555                }
13556            }
13557            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13558                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13559                        " which might be stale. Will try to clean up.");
13560                // Clean up the stale container and proceed to recreate.
13561                if (!PackageHelper.destroySdDir(newCacheId)) {
13562                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13563                    return false;
13564                }
13565                // Successfully cleaned up stale container. Try to rename again.
13566                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13567                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13568                            + " inspite of cleaning it up.");
13569                    return false;
13570                }
13571            }
13572            if (!PackageHelper.isContainerMounted(newCacheId)) {
13573                Slog.w(TAG, "Mounting container " + newCacheId);
13574                newMountPath = PackageHelper.mountSdDir(newCacheId,
13575                        getEncryptKey(), Process.SYSTEM_UID);
13576            } else {
13577                newMountPath = PackageHelper.getSdDir(newCacheId);
13578            }
13579            if (newMountPath == null) {
13580                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13581                return false;
13582            }
13583            Log.i(TAG, "Succesfully renamed " + cid +
13584                    " to " + newCacheId +
13585                    " at new path: " + newMountPath);
13586            cid = newCacheId;
13587
13588            final File beforeCodeFile = new File(packagePath);
13589            setMountPath(newMountPath);
13590            final File afterCodeFile = new File(packagePath);
13591
13592            // Reflect the rename in scanned details
13593            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13594            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13595                    afterCodeFile, pkg.baseCodePath));
13596            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13597                    afterCodeFile, pkg.splitCodePaths));
13598
13599            // Reflect the rename in app info
13600            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13601            pkg.setApplicationInfoCodePath(pkg.codePath);
13602            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13603            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13604            pkg.setApplicationInfoResourcePath(pkg.codePath);
13605            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13606            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13607
13608            return true;
13609        }
13610
13611        private void setMountPath(String mountPath) {
13612            final File mountFile = new File(mountPath);
13613
13614            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13615            if (monolithicFile.exists()) {
13616                packagePath = monolithicFile.getAbsolutePath();
13617                if (isFwdLocked()) {
13618                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13619                } else {
13620                    resourcePath = packagePath;
13621                }
13622            } else {
13623                packagePath = mountFile.getAbsolutePath();
13624                resourcePath = packagePath;
13625            }
13626        }
13627
13628        int doPostInstall(int status, int uid) {
13629            if (status != PackageManager.INSTALL_SUCCEEDED) {
13630                cleanUp();
13631            } else {
13632                final int groupOwner;
13633                final String protectedFile;
13634                if (isFwdLocked()) {
13635                    groupOwner = UserHandle.getSharedAppGid(uid);
13636                    protectedFile = RES_FILE_NAME;
13637                } else {
13638                    groupOwner = -1;
13639                    protectedFile = null;
13640                }
13641
13642                if (uid < Process.FIRST_APPLICATION_UID
13643                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13644                    Slog.e(TAG, "Failed to finalize " + cid);
13645                    PackageHelper.destroySdDir(cid);
13646                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13647                }
13648
13649                boolean mounted = PackageHelper.isContainerMounted(cid);
13650                if (!mounted) {
13651                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13652                }
13653            }
13654            return status;
13655        }
13656
13657        private void cleanUp() {
13658            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13659
13660            // Destroy secure container
13661            PackageHelper.destroySdDir(cid);
13662        }
13663
13664        private List<String> getAllCodePaths() {
13665            final File codeFile = new File(getCodePath());
13666            if (codeFile != null && codeFile.exists()) {
13667                try {
13668                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13669                    return pkg.getAllCodePaths();
13670                } catch (PackageParserException e) {
13671                    // Ignored; we tried our best
13672                }
13673            }
13674            return Collections.EMPTY_LIST;
13675        }
13676
13677        void cleanUpResourcesLI() {
13678            // Enumerate all code paths before deleting
13679            cleanUpResourcesLI(getAllCodePaths());
13680        }
13681
13682        private void cleanUpResourcesLI(List<String> allCodePaths) {
13683            cleanUp();
13684            removeDexFiles(allCodePaths, instructionSets);
13685        }
13686
13687        String getPackageName() {
13688            return getAsecPackageName(cid);
13689        }
13690
13691        boolean doPostDeleteLI(boolean delete) {
13692            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13693            final List<String> allCodePaths = getAllCodePaths();
13694            boolean mounted = PackageHelper.isContainerMounted(cid);
13695            if (mounted) {
13696                // Unmount first
13697                if (PackageHelper.unMountSdDir(cid)) {
13698                    mounted = false;
13699                }
13700            }
13701            if (!mounted && delete) {
13702                cleanUpResourcesLI(allCodePaths);
13703            }
13704            return !mounted;
13705        }
13706
13707        @Override
13708        int doPreCopy() {
13709            if (isFwdLocked()) {
13710                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13711                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13712                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13713                }
13714            }
13715
13716            return PackageManager.INSTALL_SUCCEEDED;
13717        }
13718
13719        @Override
13720        int doPostCopy(int uid) {
13721            if (isFwdLocked()) {
13722                if (uid < Process.FIRST_APPLICATION_UID
13723                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13724                                RES_FILE_NAME)) {
13725                    Slog.e(TAG, "Failed to finalize " + cid);
13726                    PackageHelper.destroySdDir(cid);
13727                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13728                }
13729            }
13730
13731            return PackageManager.INSTALL_SUCCEEDED;
13732        }
13733    }
13734
13735    /**
13736     * Logic to handle movement of existing installed applications.
13737     */
13738    class MoveInstallArgs extends InstallArgs {
13739        private File codeFile;
13740        private File resourceFile;
13741
13742        /** New install */
13743        MoveInstallArgs(InstallParams params) {
13744            super(params.origin, params.move, params.observer, params.installFlags,
13745                    params.installerPackageName, params.volumeUuid,
13746                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13747                    params.grantedRuntimePermissions,
13748                    params.traceMethod, params.traceCookie, params.certificates);
13749        }
13750
13751        int copyApk(IMediaContainerService imcs, boolean temp) {
13752            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13753                    + move.fromUuid + " to " + move.toUuid);
13754            synchronized (mInstaller) {
13755                try {
13756                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13757                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13758                } catch (InstallerException e) {
13759                    Slog.w(TAG, "Failed to move app", e);
13760                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13761                }
13762            }
13763
13764            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13765            resourceFile = codeFile;
13766            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13767
13768            return PackageManager.INSTALL_SUCCEEDED;
13769        }
13770
13771        int doPreInstall(int status) {
13772            if (status != PackageManager.INSTALL_SUCCEEDED) {
13773                cleanUp(move.toUuid);
13774            }
13775            return status;
13776        }
13777
13778        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13779            if (status != PackageManager.INSTALL_SUCCEEDED) {
13780                cleanUp(move.toUuid);
13781                return false;
13782            }
13783
13784            // Reflect the move in app info
13785            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13786            pkg.setApplicationInfoCodePath(pkg.codePath);
13787            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13788            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13789            pkg.setApplicationInfoResourcePath(pkg.codePath);
13790            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13791            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13792
13793            return true;
13794        }
13795
13796        int doPostInstall(int status, int uid) {
13797            if (status == PackageManager.INSTALL_SUCCEEDED) {
13798                cleanUp(move.fromUuid);
13799            } else {
13800                cleanUp(move.toUuid);
13801            }
13802            return status;
13803        }
13804
13805        @Override
13806        String getCodePath() {
13807            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13808        }
13809
13810        @Override
13811        String getResourcePath() {
13812            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13813        }
13814
13815        private boolean cleanUp(String volumeUuid) {
13816            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13817                    move.dataAppName);
13818            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13819            final int[] userIds = sUserManager.getUserIds();
13820            synchronized (mInstallLock) {
13821                // Clean up both app data and code
13822                // All package moves are frozen until finished
13823                for (int userId : userIds) {
13824                    try {
13825                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13826                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13827                    } catch (InstallerException e) {
13828                        Slog.w(TAG, String.valueOf(e));
13829                    }
13830                }
13831                removeCodePathLI(codeFile);
13832            }
13833            return true;
13834        }
13835
13836        void cleanUpResourcesLI() {
13837            throw new UnsupportedOperationException();
13838        }
13839
13840        boolean doPostDeleteLI(boolean delete) {
13841            throw new UnsupportedOperationException();
13842        }
13843    }
13844
13845    static String getAsecPackageName(String packageCid) {
13846        int idx = packageCid.lastIndexOf("-");
13847        if (idx == -1) {
13848            return packageCid;
13849        }
13850        return packageCid.substring(0, idx);
13851    }
13852
13853    // Utility method used to create code paths based on package name and available index.
13854    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13855        String idxStr = "";
13856        int idx = 1;
13857        // Fall back to default value of idx=1 if prefix is not
13858        // part of oldCodePath
13859        if (oldCodePath != null) {
13860            String subStr = oldCodePath;
13861            // Drop the suffix right away
13862            if (suffix != null && subStr.endsWith(suffix)) {
13863                subStr = subStr.substring(0, subStr.length() - suffix.length());
13864            }
13865            // If oldCodePath already contains prefix find out the
13866            // ending index to either increment or decrement.
13867            int sidx = subStr.lastIndexOf(prefix);
13868            if (sidx != -1) {
13869                subStr = subStr.substring(sidx + prefix.length());
13870                if (subStr != null) {
13871                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13872                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13873                    }
13874                    try {
13875                        idx = Integer.parseInt(subStr);
13876                        if (idx <= 1) {
13877                            idx++;
13878                        } else {
13879                            idx--;
13880                        }
13881                    } catch(NumberFormatException e) {
13882                    }
13883                }
13884            }
13885        }
13886        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13887        return prefix + idxStr;
13888    }
13889
13890    private File getNextCodePath(File targetDir, String packageName) {
13891        int suffix = 1;
13892        File result;
13893        do {
13894            result = new File(targetDir, packageName + "-" + suffix);
13895            suffix++;
13896        } while (result.exists());
13897        return result;
13898    }
13899
13900    // Utility method that returns the relative package path with respect
13901    // to the installation directory. Like say for /data/data/com.test-1.apk
13902    // string com.test-1 is returned.
13903    static String deriveCodePathName(String codePath) {
13904        if (codePath == null) {
13905            return null;
13906        }
13907        final File codeFile = new File(codePath);
13908        final String name = codeFile.getName();
13909        if (codeFile.isDirectory()) {
13910            return name;
13911        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13912            final int lastDot = name.lastIndexOf('.');
13913            return name.substring(0, lastDot);
13914        } else {
13915            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13916            return null;
13917        }
13918    }
13919
13920    static class PackageInstalledInfo {
13921        String name;
13922        int uid;
13923        // The set of users that originally had this package installed.
13924        int[] origUsers;
13925        // The set of users that now have this package installed.
13926        int[] newUsers;
13927        PackageParser.Package pkg;
13928        int returnCode;
13929        String returnMsg;
13930        PackageRemovedInfo removedInfo;
13931        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13932
13933        public void setError(int code, String msg) {
13934            setReturnCode(code);
13935            setReturnMessage(msg);
13936            Slog.w(TAG, msg);
13937        }
13938
13939        public void setError(String msg, PackageParserException e) {
13940            setReturnCode(e.error);
13941            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13942            Slog.w(TAG, msg, e);
13943        }
13944
13945        public void setError(String msg, PackageManagerException e) {
13946            returnCode = e.error;
13947            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13948            Slog.w(TAG, msg, e);
13949        }
13950
13951        public void setReturnCode(int returnCode) {
13952            this.returnCode = returnCode;
13953            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13954            for (int i = 0; i < childCount; i++) {
13955                addedChildPackages.valueAt(i).returnCode = returnCode;
13956            }
13957        }
13958
13959        private void setReturnMessage(String returnMsg) {
13960            this.returnMsg = returnMsg;
13961            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13962            for (int i = 0; i < childCount; i++) {
13963                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13964            }
13965        }
13966
13967        // In some error cases we want to convey more info back to the observer
13968        String origPackage;
13969        String origPermission;
13970    }
13971
13972    /*
13973     * Install a non-existing package.
13974     */
13975    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
13976            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
13977            PackageInstalledInfo res) {
13978        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13979
13980        // Remember this for later, in case we need to rollback this install
13981        String pkgName = pkg.packageName;
13982
13983        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13984
13985        synchronized(mPackages) {
13986            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13987                // A package with the same name is already installed, though
13988                // it has been renamed to an older name.  The package we
13989                // are trying to install should be installed as an update to
13990                // the existing one, but that has not been requested, so bail.
13991                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13992                        + " without first uninstalling package running as "
13993                        + mSettings.mRenamedPackages.get(pkgName));
13994                return;
13995            }
13996            if (mPackages.containsKey(pkgName)) {
13997                // Don't allow installation over an existing package with the same name.
13998                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13999                        + " without first uninstalling.");
14000                return;
14001            }
14002        }
14003
14004        try {
14005            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14006                    System.currentTimeMillis(), user);
14007
14008            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14009
14010            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14011                prepareAppDataAfterInstallLIF(newPackage);
14012
14013            } else {
14014                // Remove package from internal structures, but keep around any
14015                // data that might have already existed
14016                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14017                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14018            }
14019        } catch (PackageManagerException e) {
14020            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14021        }
14022
14023        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14024    }
14025
14026    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14027        // Can't rotate keys during boot or if sharedUser.
14028        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14029                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14030            return false;
14031        }
14032        // app is using upgradeKeySets; make sure all are valid
14033        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14034        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14035        for (int i = 0; i < upgradeKeySets.length; i++) {
14036            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14037                Slog.wtf(TAG, "Package "
14038                         + (oldPs.name != null ? oldPs.name : "<null>")
14039                         + " contains upgrade-key-set reference to unknown key-set: "
14040                         + upgradeKeySets[i]
14041                         + " reverting to signatures check.");
14042                return false;
14043            }
14044        }
14045        return true;
14046    }
14047
14048    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14049        // Upgrade keysets are being used.  Determine if new package has a superset of the
14050        // required keys.
14051        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14052        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14053        for (int i = 0; i < upgradeKeySets.length; i++) {
14054            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14055            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14056                return true;
14057            }
14058        }
14059        return false;
14060    }
14061
14062    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14063        try (DigestInputStream digestStream =
14064                new DigestInputStream(new FileInputStream(file), digest)) {
14065            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14066        }
14067    }
14068
14069    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14070            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14071        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14072
14073        final PackageParser.Package oldPackage;
14074        final String pkgName = pkg.packageName;
14075        final int[] allUsers;
14076        final int[] installedUsers;
14077
14078        synchronized(mPackages) {
14079            oldPackage = mPackages.get(pkgName);
14080            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14081
14082            // don't allow upgrade to target a release SDK from a pre-release SDK
14083            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14084                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14085            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14086                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14087            if (oldTargetsPreRelease
14088                    && !newTargetsPreRelease
14089                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14090                Slog.w(TAG, "Can't install package targeting released sdk");
14091                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14092                return;
14093            }
14094
14095            // don't allow an upgrade from full to ephemeral
14096            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14097            if (isEphemeral && !oldIsEphemeral) {
14098                // can't downgrade from full to ephemeral
14099                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14100                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14101                return;
14102            }
14103
14104            // verify signatures are valid
14105            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14106            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14107                if (!checkUpgradeKeySetLP(ps, pkg)) {
14108                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14109                            "New package not signed by keys specified by upgrade-keysets: "
14110                                    + pkgName);
14111                    return;
14112                }
14113            } else {
14114                // default to original signature matching
14115                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14116                        != PackageManager.SIGNATURE_MATCH) {
14117                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14118                            "New package has a different signature: " + pkgName);
14119                    return;
14120                }
14121            }
14122
14123            // don't allow a system upgrade unless the upgrade hash matches
14124            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14125                byte[] digestBytes = null;
14126                try {
14127                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14128                    updateDigest(digest, new File(pkg.baseCodePath));
14129                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14130                        for (String path : pkg.splitCodePaths) {
14131                            updateDigest(digest, new File(path));
14132                        }
14133                    }
14134                    digestBytes = digest.digest();
14135                } catch (NoSuchAlgorithmException | IOException e) {
14136                    res.setError(INSTALL_FAILED_INVALID_APK,
14137                            "Could not compute hash: " + pkgName);
14138                    return;
14139                }
14140                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14141                    res.setError(INSTALL_FAILED_INVALID_APK,
14142                            "New package fails restrict-update check: " + pkgName);
14143                    return;
14144                }
14145                // retain upgrade restriction
14146                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14147            }
14148
14149            // Check for shared user id changes
14150            String invalidPackageName =
14151                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14152            if (invalidPackageName != null) {
14153                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14154                        "Package " + invalidPackageName + " tried to change user "
14155                                + oldPackage.mSharedUserId);
14156                return;
14157            }
14158
14159            // In case of rollback, remember per-user/profile install state
14160            allUsers = sUserManager.getUserIds();
14161            installedUsers = ps.queryInstalledUsers(allUsers, true);
14162        }
14163
14164        // Update what is removed
14165        res.removedInfo = new PackageRemovedInfo();
14166        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14167        res.removedInfo.removedPackage = oldPackage.packageName;
14168        res.removedInfo.isUpdate = true;
14169        res.removedInfo.origUsers = installedUsers;
14170        final int childCount = (oldPackage.childPackages != null)
14171                ? oldPackage.childPackages.size() : 0;
14172        for (int i = 0; i < childCount; i++) {
14173            boolean childPackageUpdated = false;
14174            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14175            if (res.addedChildPackages != null) {
14176                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14177                if (childRes != null) {
14178                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14179                    childRes.removedInfo.removedPackage = childPkg.packageName;
14180                    childRes.removedInfo.isUpdate = true;
14181                    childPackageUpdated = true;
14182                }
14183            }
14184            if (!childPackageUpdated) {
14185                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14186                childRemovedRes.removedPackage = childPkg.packageName;
14187                childRemovedRes.isUpdate = false;
14188                childRemovedRes.dataRemoved = true;
14189                synchronized (mPackages) {
14190                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14191                    if (childPs != null) {
14192                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14193                    }
14194                }
14195                if (res.removedInfo.removedChildPackages == null) {
14196                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14197                }
14198                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14199            }
14200        }
14201
14202        boolean sysPkg = (isSystemApp(oldPackage));
14203        if (sysPkg) {
14204            // Set the system/privileged flags as needed
14205            final boolean privileged =
14206                    (oldPackage.applicationInfo.privateFlags
14207                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14208            final int systemPolicyFlags = policyFlags
14209                    | PackageParser.PARSE_IS_SYSTEM
14210                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14211
14212            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14213                    user, allUsers, installerPackageName, res);
14214        } else {
14215            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14216                    user, allUsers, installerPackageName, res);
14217        }
14218    }
14219
14220    public List<String> getPreviousCodePaths(String packageName) {
14221        final PackageSetting ps = mSettings.mPackages.get(packageName);
14222        final List<String> result = new ArrayList<String>();
14223        if (ps != null && ps.oldCodePaths != null) {
14224            result.addAll(ps.oldCodePaths);
14225        }
14226        return result;
14227    }
14228
14229    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14230            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14231            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14232        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14233                + deletedPackage);
14234
14235        String pkgName = deletedPackage.packageName;
14236        boolean deletedPkg = true;
14237        boolean addedPkg = false;
14238        boolean updatedSettings = false;
14239        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14240        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14241                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14242
14243        final long origUpdateTime = (pkg.mExtras != null)
14244                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14245
14246        // First delete the existing package while retaining the data directory
14247        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14248                res.removedInfo, true, pkg)) {
14249            // If the existing package wasn't successfully deleted
14250            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14251            deletedPkg = false;
14252        } else {
14253            // Successfully deleted the old package; proceed with replace.
14254
14255            // If deleted package lived in a container, give users a chance to
14256            // relinquish resources before killing.
14257            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14258                if (DEBUG_INSTALL) {
14259                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14260                }
14261                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14262                final ArrayList<String> pkgList = new ArrayList<String>(1);
14263                pkgList.add(deletedPackage.applicationInfo.packageName);
14264                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14265            }
14266
14267            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14268                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14269            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14270
14271            try {
14272                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14273                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14274                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14275
14276                // Update the in-memory copy of the previous code paths.
14277                PackageSetting ps = mSettings.mPackages.get(pkgName);
14278                if (!killApp) {
14279                    if (ps.oldCodePaths == null) {
14280                        ps.oldCodePaths = new ArraySet<>();
14281                    }
14282                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14283                    if (deletedPackage.splitCodePaths != null) {
14284                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14285                    }
14286                } else {
14287                    ps.oldCodePaths = null;
14288                }
14289                if (ps.childPackageNames != null) {
14290                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14291                        final String childPkgName = ps.childPackageNames.get(i);
14292                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14293                        childPs.oldCodePaths = ps.oldCodePaths;
14294                    }
14295                }
14296                prepareAppDataAfterInstallLIF(newPackage);
14297                addedPkg = true;
14298            } catch (PackageManagerException e) {
14299                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14300            }
14301        }
14302
14303        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14304            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14305
14306            // Revert all internal state mutations and added folders for the failed install
14307            if (addedPkg) {
14308                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14309                        res.removedInfo, true, null);
14310            }
14311
14312            // Restore the old package
14313            if (deletedPkg) {
14314                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14315                File restoreFile = new File(deletedPackage.codePath);
14316                // Parse old package
14317                boolean oldExternal = isExternal(deletedPackage);
14318                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14319                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14320                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14321                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14322                try {
14323                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14324                            null);
14325                } catch (PackageManagerException e) {
14326                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14327                            + e.getMessage());
14328                    return;
14329                }
14330
14331                synchronized (mPackages) {
14332                    // Ensure the installer package name up to date
14333                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14334
14335                    // Update permissions for restored package
14336                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14337
14338                    mSettings.writeLPr();
14339                }
14340
14341                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14342            }
14343        } else {
14344            synchronized (mPackages) {
14345                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14346                if (ps != null) {
14347                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14348                    if (res.removedInfo.removedChildPackages != null) {
14349                        final int childCount = res.removedInfo.removedChildPackages.size();
14350                        // Iterate in reverse as we may modify the collection
14351                        for (int i = childCount - 1; i >= 0; i--) {
14352                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14353                            if (res.addedChildPackages.containsKey(childPackageName)) {
14354                                res.removedInfo.removedChildPackages.removeAt(i);
14355                            } else {
14356                                PackageRemovedInfo childInfo = res.removedInfo
14357                                        .removedChildPackages.valueAt(i);
14358                                childInfo.removedForAllUsers = mPackages.get(
14359                                        childInfo.removedPackage) == null;
14360                            }
14361                        }
14362                    }
14363                }
14364            }
14365        }
14366    }
14367
14368    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14369            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14370            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14371        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14372                + ", old=" + deletedPackage);
14373
14374        final boolean disabledSystem;
14375
14376        // Remove existing system package
14377        removePackageLI(deletedPackage, true);
14378
14379        synchronized (mPackages) {
14380            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14381        }
14382        if (!disabledSystem) {
14383            // We didn't need to disable the .apk as a current system package,
14384            // which means we are replacing another update that is already
14385            // installed.  We need to make sure to delete the older one's .apk.
14386            res.removedInfo.args = createInstallArgsForExisting(0,
14387                    deletedPackage.applicationInfo.getCodePath(),
14388                    deletedPackage.applicationInfo.getResourcePath(),
14389                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14390        } else {
14391            res.removedInfo.args = null;
14392        }
14393
14394        // Successfully disabled the old package. Now proceed with re-installation
14395        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14396                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14397        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14398
14399        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14400        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14401                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14402
14403        PackageParser.Package newPackage = null;
14404        try {
14405            // Add the package to the internal data structures
14406            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14407
14408            // Set the update and install times
14409            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14410            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14411                    System.currentTimeMillis());
14412
14413            // Update the package dynamic state if succeeded
14414            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14415                // Now that the install succeeded make sure we remove data
14416                // directories for any child package the update removed.
14417                final int deletedChildCount = (deletedPackage.childPackages != null)
14418                        ? deletedPackage.childPackages.size() : 0;
14419                final int newChildCount = (newPackage.childPackages != null)
14420                        ? newPackage.childPackages.size() : 0;
14421                for (int i = 0; i < deletedChildCount; i++) {
14422                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14423                    boolean childPackageDeleted = true;
14424                    for (int j = 0; j < newChildCount; j++) {
14425                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14426                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14427                            childPackageDeleted = false;
14428                            break;
14429                        }
14430                    }
14431                    if (childPackageDeleted) {
14432                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14433                                deletedChildPkg.packageName);
14434                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14435                            PackageRemovedInfo removedChildRes = res.removedInfo
14436                                    .removedChildPackages.get(deletedChildPkg.packageName);
14437                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14438                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14439                        }
14440                    }
14441                }
14442
14443                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14444                prepareAppDataAfterInstallLIF(newPackage);
14445            }
14446        } catch (PackageManagerException e) {
14447            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14448            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14449        }
14450
14451        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14452            // Re installation failed. Restore old information
14453            // Remove new pkg information
14454            if (newPackage != null) {
14455                removeInstalledPackageLI(newPackage, true);
14456            }
14457            // Add back the old system package
14458            try {
14459                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14460            } catch (PackageManagerException e) {
14461                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14462            }
14463
14464            synchronized (mPackages) {
14465                if (disabledSystem) {
14466                    enableSystemPackageLPw(deletedPackage);
14467                }
14468
14469                // Ensure the installer package name up to date
14470                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14471
14472                // Update permissions for restored package
14473                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14474
14475                mSettings.writeLPr();
14476            }
14477
14478            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14479                    + " after failed upgrade");
14480        }
14481    }
14482
14483    /**
14484     * Checks whether the parent or any of the child packages have a change shared
14485     * user. For a package to be a valid update the shred users of the parent and
14486     * the children should match. We may later support changing child shared users.
14487     * @param oldPkg The updated package.
14488     * @param newPkg The update package.
14489     * @return The shared user that change between the versions.
14490     */
14491    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14492            PackageParser.Package newPkg) {
14493        // Check parent shared user
14494        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14495            return newPkg.packageName;
14496        }
14497        // Check child shared users
14498        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14499        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14500        for (int i = 0; i < newChildCount; i++) {
14501            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14502            // If this child was present, did it have the same shared user?
14503            for (int j = 0; j < oldChildCount; j++) {
14504                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14505                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14506                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14507                    return newChildPkg.packageName;
14508                }
14509            }
14510        }
14511        return null;
14512    }
14513
14514    private void removeNativeBinariesLI(PackageSetting ps) {
14515        // Remove the lib path for the parent package
14516        if (ps != null) {
14517            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14518            // Remove the lib path for the child packages
14519            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14520            for (int i = 0; i < childCount; i++) {
14521                PackageSetting childPs = null;
14522                synchronized (mPackages) {
14523                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14524                }
14525                if (childPs != null) {
14526                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14527                            .legacyNativeLibraryPathString);
14528                }
14529            }
14530        }
14531    }
14532
14533    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14534        // Enable the parent package
14535        mSettings.enableSystemPackageLPw(pkg.packageName);
14536        // Enable the child packages
14537        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14538        for (int i = 0; i < childCount; i++) {
14539            PackageParser.Package childPkg = pkg.childPackages.get(i);
14540            mSettings.enableSystemPackageLPw(childPkg.packageName);
14541        }
14542    }
14543
14544    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14545            PackageParser.Package newPkg) {
14546        // Disable the parent package (parent always replaced)
14547        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14548        // Disable the child packages
14549        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14550        for (int i = 0; i < childCount; i++) {
14551            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14552            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14553            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14554        }
14555        return disabled;
14556    }
14557
14558    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14559            String installerPackageName) {
14560        // Enable the parent package
14561        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14562        // Enable the child packages
14563        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14564        for (int i = 0; i < childCount; i++) {
14565            PackageParser.Package childPkg = pkg.childPackages.get(i);
14566            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14567        }
14568    }
14569
14570    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14571        // Collect all used permissions in the UID
14572        ArraySet<String> usedPermissions = new ArraySet<>();
14573        final int packageCount = su.packages.size();
14574        for (int i = 0; i < packageCount; i++) {
14575            PackageSetting ps = su.packages.valueAt(i);
14576            if (ps.pkg == null) {
14577                continue;
14578            }
14579            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14580            for (int j = 0; j < requestedPermCount; j++) {
14581                String permission = ps.pkg.requestedPermissions.get(j);
14582                BasePermission bp = mSettings.mPermissions.get(permission);
14583                if (bp != null) {
14584                    usedPermissions.add(permission);
14585                }
14586            }
14587        }
14588
14589        PermissionsState permissionsState = su.getPermissionsState();
14590        // Prune install permissions
14591        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14592        final int installPermCount = installPermStates.size();
14593        for (int i = installPermCount - 1; i >= 0;  i--) {
14594            PermissionState permissionState = installPermStates.get(i);
14595            if (!usedPermissions.contains(permissionState.getName())) {
14596                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14597                if (bp != null) {
14598                    permissionsState.revokeInstallPermission(bp);
14599                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14600                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14601                }
14602            }
14603        }
14604
14605        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14606
14607        // Prune runtime permissions
14608        for (int userId : allUserIds) {
14609            List<PermissionState> runtimePermStates = permissionsState
14610                    .getRuntimePermissionStates(userId);
14611            final int runtimePermCount = runtimePermStates.size();
14612            for (int i = runtimePermCount - 1; i >= 0; i--) {
14613                PermissionState permissionState = runtimePermStates.get(i);
14614                if (!usedPermissions.contains(permissionState.getName())) {
14615                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14616                    if (bp != null) {
14617                        permissionsState.revokeRuntimePermission(bp, userId);
14618                        permissionsState.updatePermissionFlags(bp, userId,
14619                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14620                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14621                                runtimePermissionChangedUserIds, userId);
14622                    }
14623                }
14624            }
14625        }
14626
14627        return runtimePermissionChangedUserIds;
14628    }
14629
14630    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14631            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14632        // Update the parent package setting
14633        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14634                res, user);
14635        // Update the child packages setting
14636        final int childCount = (newPackage.childPackages != null)
14637                ? newPackage.childPackages.size() : 0;
14638        for (int i = 0; i < childCount; i++) {
14639            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14640            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14641            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14642                    childRes.origUsers, childRes, user);
14643        }
14644    }
14645
14646    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14647            String installerPackageName, int[] allUsers, int[] installedForUsers,
14648            PackageInstalledInfo res, UserHandle user) {
14649        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14650
14651        String pkgName = newPackage.packageName;
14652        synchronized (mPackages) {
14653            //write settings. the installStatus will be incomplete at this stage.
14654            //note that the new package setting would have already been
14655            //added to mPackages. It hasn't been persisted yet.
14656            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14657            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14658            mSettings.writeLPr();
14659            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14660        }
14661
14662        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14663        synchronized (mPackages) {
14664            updatePermissionsLPw(newPackage.packageName, newPackage,
14665                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14666                            ? UPDATE_PERMISSIONS_ALL : 0));
14667            // For system-bundled packages, we assume that installing an upgraded version
14668            // of the package implies that the user actually wants to run that new code,
14669            // so we enable the package.
14670            PackageSetting ps = mSettings.mPackages.get(pkgName);
14671            final int userId = user.getIdentifier();
14672            if (ps != null) {
14673                if (isSystemApp(newPackage)) {
14674                    if (DEBUG_INSTALL) {
14675                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14676                    }
14677                    // Enable system package for requested users
14678                    if (res.origUsers != null) {
14679                        for (int origUserId : res.origUsers) {
14680                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14681                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14682                                        origUserId, installerPackageName);
14683                            }
14684                        }
14685                    }
14686                    // Also convey the prior install/uninstall state
14687                    if (allUsers != null && installedForUsers != null) {
14688                        for (int currentUserId : allUsers) {
14689                            final boolean installed = ArrayUtils.contains(
14690                                    installedForUsers, currentUserId);
14691                            if (DEBUG_INSTALL) {
14692                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14693                            }
14694                            ps.setInstalled(installed, currentUserId);
14695                        }
14696                        // these install state changes will be persisted in the
14697                        // upcoming call to mSettings.writeLPr().
14698                    }
14699                }
14700                // It's implied that when a user requests installation, they want the app to be
14701                // installed and enabled.
14702                if (userId != UserHandle.USER_ALL) {
14703                    ps.setInstalled(true, userId);
14704                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14705                }
14706            }
14707            res.name = pkgName;
14708            res.uid = newPackage.applicationInfo.uid;
14709            res.pkg = newPackage;
14710            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14711            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14712            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14713            //to update install status
14714            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14715            mSettings.writeLPr();
14716            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14717        }
14718
14719        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14720    }
14721
14722    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14723        try {
14724            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14725            installPackageLI(args, res);
14726        } finally {
14727            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14728        }
14729    }
14730
14731    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14732        final int installFlags = args.installFlags;
14733        final String installerPackageName = args.installerPackageName;
14734        final String volumeUuid = args.volumeUuid;
14735        final File tmpPackageFile = new File(args.getCodePath());
14736        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14737        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14738                || (args.volumeUuid != null));
14739        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14740        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14741        boolean replace = false;
14742        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14743        if (args.move != null) {
14744            // moving a complete application; perform an initial scan on the new install location
14745            scanFlags |= SCAN_INITIAL;
14746        }
14747        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14748            scanFlags |= SCAN_DONT_KILL_APP;
14749        }
14750
14751        // Result object to be returned
14752        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14753
14754        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14755
14756        // Sanity check
14757        if (ephemeral && (forwardLocked || onExternal)) {
14758            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14759                    + " external=" + onExternal);
14760            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14761            return;
14762        }
14763
14764        // Retrieve PackageSettings and parse package
14765        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14766                | PackageParser.PARSE_ENFORCE_CODE
14767                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14768                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14769                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14770                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14771        PackageParser pp = new PackageParser();
14772        pp.setSeparateProcesses(mSeparateProcesses);
14773        pp.setDisplayMetrics(mMetrics);
14774
14775        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14776        final PackageParser.Package pkg;
14777        try {
14778            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14779        } catch (PackageParserException e) {
14780            res.setError("Failed parse during installPackageLI", e);
14781            return;
14782        } finally {
14783            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14784        }
14785
14786        // If we are installing a clustered package add results for the children
14787        if (pkg.childPackages != null) {
14788            synchronized (mPackages) {
14789                final int childCount = pkg.childPackages.size();
14790                for (int i = 0; i < childCount; i++) {
14791                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14792                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14793                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14794                    childRes.pkg = childPkg;
14795                    childRes.name = childPkg.packageName;
14796                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14797                    if (childPs != null) {
14798                        childRes.origUsers = childPs.queryInstalledUsers(
14799                                sUserManager.getUserIds(), true);
14800                    }
14801                    if ((mPackages.containsKey(childPkg.packageName))) {
14802                        childRes.removedInfo = new PackageRemovedInfo();
14803                        childRes.removedInfo.removedPackage = childPkg.packageName;
14804                    }
14805                    if (res.addedChildPackages == null) {
14806                        res.addedChildPackages = new ArrayMap<>();
14807                    }
14808                    res.addedChildPackages.put(childPkg.packageName, childRes);
14809                }
14810            }
14811        }
14812
14813        // If package doesn't declare API override, mark that we have an install
14814        // time CPU ABI override.
14815        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14816            pkg.cpuAbiOverride = args.abiOverride;
14817        }
14818
14819        String pkgName = res.name = pkg.packageName;
14820        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14821            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14822                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14823                return;
14824            }
14825        }
14826
14827        try {
14828            // either use what we've been given or parse directly from the APK
14829            if (args.certificates != null) {
14830                try {
14831                    PackageParser.populateCertificates(pkg, args.certificates);
14832                } catch (PackageParserException e) {
14833                    // there was something wrong with the certificates we were given;
14834                    // try to pull them from the APK
14835                    PackageParser.collectCertificates(pkg, parseFlags);
14836                }
14837            } else {
14838                PackageParser.collectCertificates(pkg, parseFlags);
14839            }
14840        } catch (PackageParserException e) {
14841            res.setError("Failed collect during installPackageLI", e);
14842            return;
14843        }
14844
14845        // Get rid of all references to package scan path via parser.
14846        pp = null;
14847        String oldCodePath = null;
14848        boolean systemApp = false;
14849        synchronized (mPackages) {
14850            // Check if installing already existing package
14851            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14852                String oldName = mSettings.mRenamedPackages.get(pkgName);
14853                if (pkg.mOriginalPackages != null
14854                        && pkg.mOriginalPackages.contains(oldName)
14855                        && mPackages.containsKey(oldName)) {
14856                    // This package is derived from an original package,
14857                    // and this device has been updating from that original
14858                    // name.  We must continue using the original name, so
14859                    // rename the new package here.
14860                    pkg.setPackageName(oldName);
14861                    pkgName = pkg.packageName;
14862                    replace = true;
14863                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14864                            + oldName + " pkgName=" + pkgName);
14865                } else if (mPackages.containsKey(pkgName)) {
14866                    // This package, under its official name, already exists
14867                    // on the device; we should replace it.
14868                    replace = true;
14869                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14870                }
14871
14872                // Child packages are installed through the parent package
14873                if (pkg.parentPackage != null) {
14874                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14875                            "Package " + pkg.packageName + " is child of package "
14876                                    + pkg.parentPackage.parentPackage + ". Child packages "
14877                                    + "can be updated only through the parent package.");
14878                    return;
14879                }
14880
14881                if (replace) {
14882                    // Prevent apps opting out from runtime permissions
14883                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14884                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14885                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14886                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14887                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14888                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14889                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14890                                        + " doesn't support runtime permissions but the old"
14891                                        + " target SDK " + oldTargetSdk + " does.");
14892                        return;
14893                    }
14894
14895                    // Prevent installing of child packages
14896                    if (oldPackage.parentPackage != null) {
14897                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14898                                "Package " + pkg.packageName + " is child of package "
14899                                        + oldPackage.parentPackage + ". Child packages "
14900                                        + "can be updated only through the parent package.");
14901                        return;
14902                    }
14903                }
14904            }
14905
14906            PackageSetting ps = mSettings.mPackages.get(pkgName);
14907            if (ps != null) {
14908                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14909
14910                // Quick sanity check that we're signed correctly if updating;
14911                // we'll check this again later when scanning, but we want to
14912                // bail early here before tripping over redefined permissions.
14913                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14914                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14915                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14916                                + pkg.packageName + " upgrade keys do not match the "
14917                                + "previously installed version");
14918                        return;
14919                    }
14920                } else {
14921                    try {
14922                        verifySignaturesLP(ps, pkg);
14923                    } catch (PackageManagerException e) {
14924                        res.setError(e.error, e.getMessage());
14925                        return;
14926                    }
14927                }
14928
14929                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14930                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14931                    systemApp = (ps.pkg.applicationInfo.flags &
14932                            ApplicationInfo.FLAG_SYSTEM) != 0;
14933                }
14934                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14935            }
14936
14937            // Check whether the newly-scanned package wants to define an already-defined perm
14938            int N = pkg.permissions.size();
14939            for (int i = N-1; i >= 0; i--) {
14940                PackageParser.Permission perm = pkg.permissions.get(i);
14941                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14942                if (bp != null) {
14943                    // If the defining package is signed with our cert, it's okay.  This
14944                    // also includes the "updating the same package" case, of course.
14945                    // "updating same package" could also involve key-rotation.
14946                    final boolean sigsOk;
14947                    if (bp.sourcePackage.equals(pkg.packageName)
14948                            && (bp.packageSetting instanceof PackageSetting)
14949                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14950                                    scanFlags))) {
14951                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14952                    } else {
14953                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14954                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14955                    }
14956                    if (!sigsOk) {
14957                        // If the owning package is the system itself, we log but allow
14958                        // install to proceed; we fail the install on all other permission
14959                        // redefinitions.
14960                        if (!bp.sourcePackage.equals("android")) {
14961                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14962                                    + pkg.packageName + " attempting to redeclare permission "
14963                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14964                            res.origPermission = perm.info.name;
14965                            res.origPackage = bp.sourcePackage;
14966                            return;
14967                        } else {
14968                            Slog.w(TAG, "Package " + pkg.packageName
14969                                    + " attempting to redeclare system permission "
14970                                    + perm.info.name + "; ignoring new declaration");
14971                            pkg.permissions.remove(i);
14972                        }
14973                    }
14974                }
14975            }
14976        }
14977
14978        if (systemApp) {
14979            if (onExternal) {
14980                // Abort update; system app can't be replaced with app on sdcard
14981                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14982                        "Cannot install updates to system apps on sdcard");
14983                return;
14984            } else if (ephemeral) {
14985                // Abort update; system app can't be replaced with an ephemeral app
14986                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14987                        "Cannot update a system app with an ephemeral app");
14988                return;
14989            }
14990        }
14991
14992        if (args.move != null) {
14993            // We did an in-place move, so dex is ready to roll
14994            scanFlags |= SCAN_NO_DEX;
14995            scanFlags |= SCAN_MOVE;
14996
14997            synchronized (mPackages) {
14998                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14999                if (ps == null) {
15000                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15001                            "Missing settings for moved package " + pkgName);
15002                }
15003
15004                // We moved the entire application as-is, so bring over the
15005                // previously derived ABI information.
15006                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15007                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15008            }
15009
15010        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15011            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15012            scanFlags |= SCAN_NO_DEX;
15013
15014            try {
15015                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15016                    args.abiOverride : pkg.cpuAbiOverride);
15017                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15018                        true /* extract libs */);
15019            } catch (PackageManagerException pme) {
15020                Slog.e(TAG, "Error deriving application ABI", pme);
15021                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15022                return;
15023            }
15024
15025            // Shared libraries for the package need to be updated.
15026            synchronized (mPackages) {
15027                try {
15028                    updateSharedLibrariesLPw(pkg, null);
15029                } catch (PackageManagerException e) {
15030                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15031                }
15032            }
15033            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15034            // Do not run PackageDexOptimizer through the local performDexOpt
15035            // method because `pkg` may not be in `mPackages` yet.
15036            //
15037            // Also, don't fail application installs if the dexopt step fails.
15038            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15039                    null /* instructionSets */, false /* checkProfiles */,
15040                    getCompilerFilterForReason(REASON_INSTALL),
15041                    getOrCreateCompilerPackageStats(pkg));
15042            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15043
15044            // Notify BackgroundDexOptService that the package has been changed.
15045            // If this is an update of a package which used to fail to compile,
15046            // BDOS will remove it from its blacklist.
15047            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15048        }
15049
15050        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15051            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15052            return;
15053        }
15054
15055        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15056
15057        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15058                "installPackageLI")) {
15059            if (replace) {
15060                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15061                        installerPackageName, res);
15062            } else {
15063                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15064                        args.user, installerPackageName, volumeUuid, res);
15065            }
15066        }
15067        synchronized (mPackages) {
15068            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15069            if (ps != null) {
15070                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15071            }
15072
15073            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15074            for (int i = 0; i < childCount; i++) {
15075                PackageParser.Package childPkg = pkg.childPackages.get(i);
15076                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15077                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15078                if (childPs != null) {
15079                    childRes.newUsers = childPs.queryInstalledUsers(
15080                            sUserManager.getUserIds(), true);
15081                }
15082            }
15083        }
15084    }
15085
15086    private void startIntentFilterVerifications(int userId, boolean replacing,
15087            PackageParser.Package pkg) {
15088        if (mIntentFilterVerifierComponent == null) {
15089            Slog.w(TAG, "No IntentFilter verification will not be done as "
15090                    + "there is no IntentFilterVerifier available!");
15091            return;
15092        }
15093
15094        final int verifierUid = getPackageUid(
15095                mIntentFilterVerifierComponent.getPackageName(),
15096                MATCH_DEBUG_TRIAGED_MISSING,
15097                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15098
15099        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15100        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15101        mHandler.sendMessage(msg);
15102
15103        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15104        for (int i = 0; i < childCount; i++) {
15105            PackageParser.Package childPkg = pkg.childPackages.get(i);
15106            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15107            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15108            mHandler.sendMessage(msg);
15109        }
15110    }
15111
15112    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15113            PackageParser.Package pkg) {
15114        int size = pkg.activities.size();
15115        if (size == 0) {
15116            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15117                    "No activity, so no need to verify any IntentFilter!");
15118            return;
15119        }
15120
15121        final boolean hasDomainURLs = hasDomainURLs(pkg);
15122        if (!hasDomainURLs) {
15123            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15124                    "No domain URLs, so no need to verify any IntentFilter!");
15125            return;
15126        }
15127
15128        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15129                + " if any IntentFilter from the " + size
15130                + " Activities needs verification ...");
15131
15132        int count = 0;
15133        final String packageName = pkg.packageName;
15134
15135        synchronized (mPackages) {
15136            // If this is a new install and we see that we've already run verification for this
15137            // package, we have nothing to do: it means the state was restored from backup.
15138            if (!replacing) {
15139                IntentFilterVerificationInfo ivi =
15140                        mSettings.getIntentFilterVerificationLPr(packageName);
15141                if (ivi != null) {
15142                    if (DEBUG_DOMAIN_VERIFICATION) {
15143                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15144                                + ivi.getStatusString());
15145                    }
15146                    return;
15147                }
15148            }
15149
15150            // If any filters need to be verified, then all need to be.
15151            boolean needToVerify = false;
15152            for (PackageParser.Activity a : pkg.activities) {
15153                for (ActivityIntentInfo filter : a.intents) {
15154                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15155                        if (DEBUG_DOMAIN_VERIFICATION) {
15156                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15157                        }
15158                        needToVerify = true;
15159                        break;
15160                    }
15161                }
15162            }
15163
15164            if (needToVerify) {
15165                final int verificationId = mIntentFilterVerificationToken++;
15166                for (PackageParser.Activity a : pkg.activities) {
15167                    for (ActivityIntentInfo filter : a.intents) {
15168                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15169                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15170                                    "Verification needed for IntentFilter:" + filter.toString());
15171                            mIntentFilterVerifier.addOneIntentFilterVerification(
15172                                    verifierUid, userId, verificationId, filter, packageName);
15173                            count++;
15174                        }
15175                    }
15176                }
15177            }
15178        }
15179
15180        if (count > 0) {
15181            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15182                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15183                    +  " for userId:" + userId);
15184            mIntentFilterVerifier.startVerifications(userId);
15185        } else {
15186            if (DEBUG_DOMAIN_VERIFICATION) {
15187                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15188            }
15189        }
15190    }
15191
15192    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15193        final ComponentName cn  = filter.activity.getComponentName();
15194        final String packageName = cn.getPackageName();
15195
15196        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15197                packageName);
15198        if (ivi == null) {
15199            return true;
15200        }
15201        int status = ivi.getStatus();
15202        switch (status) {
15203            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15204            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15205                return true;
15206
15207            default:
15208                // Nothing to do
15209                return false;
15210        }
15211    }
15212
15213    private static boolean isMultiArch(ApplicationInfo info) {
15214        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15215    }
15216
15217    private static boolean isExternal(PackageParser.Package pkg) {
15218        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15219    }
15220
15221    private static boolean isExternal(PackageSetting ps) {
15222        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15223    }
15224
15225    private static boolean isEphemeral(PackageParser.Package pkg) {
15226        return pkg.applicationInfo.isEphemeralApp();
15227    }
15228
15229    private static boolean isEphemeral(PackageSetting ps) {
15230        return ps.pkg != null && isEphemeral(ps.pkg);
15231    }
15232
15233    private static boolean isSystemApp(PackageParser.Package pkg) {
15234        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15235    }
15236
15237    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15238        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15239    }
15240
15241    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15242        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15243    }
15244
15245    private static boolean isSystemApp(PackageSetting ps) {
15246        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15247    }
15248
15249    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15250        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15251    }
15252
15253    private int packageFlagsToInstallFlags(PackageSetting ps) {
15254        int installFlags = 0;
15255        if (isEphemeral(ps)) {
15256            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15257        }
15258        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15259            // This existing package was an external ASEC install when we have
15260            // the external flag without a UUID
15261            installFlags |= PackageManager.INSTALL_EXTERNAL;
15262        }
15263        if (ps.isForwardLocked()) {
15264            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15265        }
15266        return installFlags;
15267    }
15268
15269    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15270        if (isExternal(pkg)) {
15271            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15272                return StorageManager.UUID_PRIMARY_PHYSICAL;
15273            } else {
15274                return pkg.volumeUuid;
15275            }
15276        } else {
15277            return StorageManager.UUID_PRIVATE_INTERNAL;
15278        }
15279    }
15280
15281    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15282        if (isExternal(pkg)) {
15283            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15284                return mSettings.getExternalVersion();
15285            } else {
15286                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15287            }
15288        } else {
15289            return mSettings.getInternalVersion();
15290        }
15291    }
15292
15293    private void deleteTempPackageFiles() {
15294        final FilenameFilter filter = new FilenameFilter() {
15295            public boolean accept(File dir, String name) {
15296                return name.startsWith("vmdl") && name.endsWith(".tmp");
15297            }
15298        };
15299        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15300            file.delete();
15301        }
15302    }
15303
15304    @Override
15305    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15306            int flags) {
15307        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15308                flags);
15309    }
15310
15311    @Override
15312    public void deletePackage(final String packageName,
15313            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15314        mContext.enforceCallingOrSelfPermission(
15315                android.Manifest.permission.DELETE_PACKAGES, null);
15316        Preconditions.checkNotNull(packageName);
15317        Preconditions.checkNotNull(observer);
15318        final int uid = Binder.getCallingUid();
15319        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15320        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15321        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15322            mContext.enforceCallingOrSelfPermission(
15323                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15324                    "deletePackage for user " + userId);
15325        }
15326
15327        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15328            try {
15329                observer.onPackageDeleted(packageName,
15330                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15331            } catch (RemoteException re) {
15332            }
15333            return;
15334        }
15335
15336        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15337            try {
15338                observer.onPackageDeleted(packageName,
15339                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15340            } catch (RemoteException re) {
15341            }
15342            return;
15343        }
15344
15345        if (DEBUG_REMOVE) {
15346            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15347                    + " deleteAllUsers: " + deleteAllUsers );
15348        }
15349        // Queue up an async operation since the package deletion may take a little while.
15350        mHandler.post(new Runnable() {
15351            public void run() {
15352                mHandler.removeCallbacks(this);
15353                int returnCode;
15354                if (!deleteAllUsers) {
15355                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15356                } else {
15357                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15358                    // If nobody is blocking uninstall, proceed with delete for all users
15359                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15360                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15361                    } else {
15362                        // Otherwise uninstall individually for users with blockUninstalls=false
15363                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15364                        for (int userId : users) {
15365                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15366                                returnCode = deletePackageX(packageName, userId, userFlags);
15367                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15368                                    Slog.w(TAG, "Package delete failed for user " + userId
15369                                            + ", returnCode " + returnCode);
15370                                }
15371                            }
15372                        }
15373                        // The app has only been marked uninstalled for certain users.
15374                        // We still need to report that delete was blocked
15375                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15376                    }
15377                }
15378                try {
15379                    observer.onPackageDeleted(packageName, returnCode, null);
15380                } catch (RemoteException e) {
15381                    Log.i(TAG, "Observer no longer exists.");
15382                } //end catch
15383            } //end run
15384        });
15385    }
15386
15387    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15388        int[] result = EMPTY_INT_ARRAY;
15389        for (int userId : userIds) {
15390            if (getBlockUninstallForUser(packageName, userId)) {
15391                result = ArrayUtils.appendInt(result, userId);
15392            }
15393        }
15394        return result;
15395    }
15396
15397    @Override
15398    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15399        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15400    }
15401
15402    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15403        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15404                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15405        try {
15406            if (dpm != null) {
15407                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15408                        /* callingUserOnly =*/ false);
15409                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15410                        : deviceOwnerComponentName.getPackageName();
15411                // Does the package contains the device owner?
15412                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15413                // this check is probably not needed, since DO should be registered as a device
15414                // admin on some user too. (Original bug for this: b/17657954)
15415                if (packageName.equals(deviceOwnerPackageName)) {
15416                    return true;
15417                }
15418                // Does it contain a device admin for any user?
15419                int[] users;
15420                if (userId == UserHandle.USER_ALL) {
15421                    users = sUserManager.getUserIds();
15422                } else {
15423                    users = new int[]{userId};
15424                }
15425                for (int i = 0; i < users.length; ++i) {
15426                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15427                        return true;
15428                    }
15429                }
15430            }
15431        } catch (RemoteException e) {
15432        }
15433        return false;
15434    }
15435
15436    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15437        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15438    }
15439
15440    /**
15441     *  This method is an internal method that could be get invoked either
15442     *  to delete an installed package or to clean up a failed installation.
15443     *  After deleting an installed package, a broadcast is sent to notify any
15444     *  listeners that the package has been removed. For cleaning up a failed
15445     *  installation, the broadcast is not necessary since the package's
15446     *  installation wouldn't have sent the initial broadcast either
15447     *  The key steps in deleting a package are
15448     *  deleting the package information in internal structures like mPackages,
15449     *  deleting the packages base directories through installd
15450     *  updating mSettings to reflect current status
15451     *  persisting settings for later use
15452     *  sending a broadcast if necessary
15453     */
15454    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15455        final PackageRemovedInfo info = new PackageRemovedInfo();
15456        final boolean res;
15457
15458        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15459                ? UserHandle.USER_ALL : userId;
15460
15461        if (isPackageDeviceAdmin(packageName, removeUser)) {
15462            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15463            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15464        }
15465
15466        PackageSetting uninstalledPs = null;
15467
15468        // for the uninstall-updates case and restricted profiles, remember the per-
15469        // user handle installed state
15470        int[] allUsers;
15471        synchronized (mPackages) {
15472            uninstalledPs = mSettings.mPackages.get(packageName);
15473            if (uninstalledPs == null) {
15474                Slog.w(TAG, "Not removing non-existent package " + packageName);
15475                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15476            }
15477            allUsers = sUserManager.getUserIds();
15478            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15479        }
15480
15481        final int freezeUser;
15482        if (isUpdatedSystemApp(uninstalledPs)
15483                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15484            // We're downgrading a system app, which will apply to all users, so
15485            // freeze them all during the downgrade
15486            freezeUser = UserHandle.USER_ALL;
15487        } else {
15488            freezeUser = removeUser;
15489        }
15490
15491        synchronized (mInstallLock) {
15492            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15493            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15494                    deleteFlags, "deletePackageX")) {
15495                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15496                        deleteFlags | REMOVE_CHATTY, info, true, null);
15497            }
15498            synchronized (mPackages) {
15499                if (res) {
15500                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15501                }
15502            }
15503        }
15504
15505        if (res) {
15506            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15507            info.sendPackageRemovedBroadcasts(killApp);
15508            info.sendSystemPackageUpdatedBroadcasts();
15509            info.sendSystemPackageAppearedBroadcasts();
15510        }
15511        // Force a gc here.
15512        Runtime.getRuntime().gc();
15513        // Delete the resources here after sending the broadcast to let
15514        // other processes clean up before deleting resources.
15515        if (info.args != null) {
15516            synchronized (mInstallLock) {
15517                info.args.doPostDeleteLI(true);
15518            }
15519        }
15520
15521        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15522    }
15523
15524    class PackageRemovedInfo {
15525        String removedPackage;
15526        int uid = -1;
15527        int removedAppId = -1;
15528        int[] origUsers;
15529        int[] removedUsers = null;
15530        boolean isRemovedPackageSystemUpdate = false;
15531        boolean isUpdate;
15532        boolean dataRemoved;
15533        boolean removedForAllUsers;
15534        // Clean up resources deleted packages.
15535        InstallArgs args = null;
15536        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15537        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15538
15539        void sendPackageRemovedBroadcasts(boolean killApp) {
15540            sendPackageRemovedBroadcastInternal(killApp);
15541            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15542            for (int i = 0; i < childCount; i++) {
15543                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15544                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15545            }
15546        }
15547
15548        void sendSystemPackageUpdatedBroadcasts() {
15549            if (isRemovedPackageSystemUpdate) {
15550                sendSystemPackageUpdatedBroadcastsInternal();
15551                final int childCount = (removedChildPackages != null)
15552                        ? removedChildPackages.size() : 0;
15553                for (int i = 0; i < childCount; i++) {
15554                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15555                    if (childInfo.isRemovedPackageSystemUpdate) {
15556                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15557                    }
15558                }
15559            }
15560        }
15561
15562        void sendSystemPackageAppearedBroadcasts() {
15563            final int packageCount = (appearedChildPackages != null)
15564                    ? appearedChildPackages.size() : 0;
15565            for (int i = 0; i < packageCount; i++) {
15566                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15567                for (int userId : installedInfo.newUsers) {
15568                    sendPackageAddedForUser(installedInfo.name, true,
15569                            UserHandle.getAppId(installedInfo.uid), userId);
15570                }
15571            }
15572        }
15573
15574        private void sendSystemPackageUpdatedBroadcastsInternal() {
15575            Bundle extras = new Bundle(2);
15576            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15577            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15578            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15579                    extras, 0, null, null, null);
15580            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15581                    extras, 0, null, null, null);
15582            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15583                    null, 0, removedPackage, null, null);
15584        }
15585
15586        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15587            Bundle extras = new Bundle(2);
15588            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15589            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15590            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15591            if (isUpdate || isRemovedPackageSystemUpdate) {
15592                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15593            }
15594            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15595            if (removedPackage != null) {
15596                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15597                        extras, 0, null, null, removedUsers);
15598                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15599                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15600                            removedPackage, extras, 0, null, null, removedUsers);
15601                }
15602            }
15603            if (removedAppId >= 0) {
15604                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15605                        removedUsers);
15606            }
15607        }
15608    }
15609
15610    /*
15611     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15612     * flag is not set, the data directory is removed as well.
15613     * make sure this flag is set for partially installed apps. If not its meaningless to
15614     * delete a partially installed application.
15615     */
15616    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15617            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15618        String packageName = ps.name;
15619        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15620        // Retrieve object to delete permissions for shared user later on
15621        final PackageParser.Package deletedPkg;
15622        final PackageSetting deletedPs;
15623        // reader
15624        synchronized (mPackages) {
15625            deletedPkg = mPackages.get(packageName);
15626            deletedPs = mSettings.mPackages.get(packageName);
15627            if (outInfo != null) {
15628                outInfo.removedPackage = packageName;
15629                outInfo.removedUsers = deletedPs != null
15630                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15631                        : null;
15632            }
15633        }
15634
15635        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15636
15637        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15638            final PackageParser.Package resolvedPkg;
15639            if (deletedPkg != null) {
15640                resolvedPkg = deletedPkg;
15641            } else {
15642                // We don't have a parsed package when it lives on an ejected
15643                // adopted storage device, so fake something together
15644                resolvedPkg = new PackageParser.Package(ps.name);
15645                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15646            }
15647            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15648                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15649            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15650            if (outInfo != null) {
15651                outInfo.dataRemoved = true;
15652            }
15653            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15654        }
15655
15656        // writer
15657        synchronized (mPackages) {
15658            if (deletedPs != null) {
15659                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15660                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15661                    clearDefaultBrowserIfNeeded(packageName);
15662                    if (outInfo != null) {
15663                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15664                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15665                    }
15666                    updatePermissionsLPw(deletedPs.name, null, 0);
15667                    if (deletedPs.sharedUser != null) {
15668                        // Remove permissions associated with package. Since runtime
15669                        // permissions are per user we have to kill the removed package
15670                        // or packages running under the shared user of the removed
15671                        // package if revoking the permissions requested only by the removed
15672                        // package is successful and this causes a change in gids.
15673                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15674                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15675                                    userId);
15676                            if (userIdToKill == UserHandle.USER_ALL
15677                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15678                                // If gids changed for this user, kill all affected packages.
15679                                mHandler.post(new Runnable() {
15680                                    @Override
15681                                    public void run() {
15682                                        // This has to happen with no lock held.
15683                                        killApplication(deletedPs.name, deletedPs.appId,
15684                                                KILL_APP_REASON_GIDS_CHANGED);
15685                                    }
15686                                });
15687                                break;
15688                            }
15689                        }
15690                    }
15691                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15692                }
15693                // make sure to preserve per-user disabled state if this removal was just
15694                // a downgrade of a system app to the factory package
15695                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15696                    if (DEBUG_REMOVE) {
15697                        Slog.d(TAG, "Propagating install state across downgrade");
15698                    }
15699                    for (int userId : allUserHandles) {
15700                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15701                        if (DEBUG_REMOVE) {
15702                            Slog.d(TAG, "    user " + userId + " => " + installed);
15703                        }
15704                        ps.setInstalled(installed, userId);
15705                    }
15706                }
15707            }
15708            // can downgrade to reader
15709            if (writeSettings) {
15710                // Save settings now
15711                mSettings.writeLPr();
15712            }
15713        }
15714        if (outInfo != null) {
15715            // A user ID was deleted here. Go through all users and remove it
15716            // from KeyStore.
15717            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15718        }
15719    }
15720
15721    static boolean locationIsPrivileged(File path) {
15722        try {
15723            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15724                    .getCanonicalPath();
15725            return path.getCanonicalPath().startsWith(privilegedAppDir);
15726        } catch (IOException e) {
15727            Slog.e(TAG, "Unable to access code path " + path);
15728        }
15729        return false;
15730    }
15731
15732    /*
15733     * Tries to delete system package.
15734     */
15735    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15736            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15737            boolean writeSettings) {
15738        if (deletedPs.parentPackageName != null) {
15739            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15740            return false;
15741        }
15742
15743        final boolean applyUserRestrictions
15744                = (allUserHandles != null) && (outInfo.origUsers != null);
15745        final PackageSetting disabledPs;
15746        // Confirm if the system package has been updated
15747        // An updated system app can be deleted. This will also have to restore
15748        // the system pkg from system partition
15749        // reader
15750        synchronized (mPackages) {
15751            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15752        }
15753
15754        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15755                + " disabledPs=" + disabledPs);
15756
15757        if (disabledPs == null) {
15758            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15759            return false;
15760        } else if (DEBUG_REMOVE) {
15761            Slog.d(TAG, "Deleting system pkg from data partition");
15762        }
15763
15764        if (DEBUG_REMOVE) {
15765            if (applyUserRestrictions) {
15766                Slog.d(TAG, "Remembering install states:");
15767                for (int userId : allUserHandles) {
15768                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15769                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15770                }
15771            }
15772        }
15773
15774        // Delete the updated package
15775        outInfo.isRemovedPackageSystemUpdate = true;
15776        if (outInfo.removedChildPackages != null) {
15777            final int childCount = (deletedPs.childPackageNames != null)
15778                    ? deletedPs.childPackageNames.size() : 0;
15779            for (int i = 0; i < childCount; i++) {
15780                String childPackageName = deletedPs.childPackageNames.get(i);
15781                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15782                        .contains(childPackageName)) {
15783                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15784                            childPackageName);
15785                    if (childInfo != null) {
15786                        childInfo.isRemovedPackageSystemUpdate = true;
15787                    }
15788                }
15789            }
15790        }
15791
15792        if (disabledPs.versionCode < deletedPs.versionCode) {
15793            // Delete data for downgrades
15794            flags &= ~PackageManager.DELETE_KEEP_DATA;
15795        } else {
15796            // Preserve data by setting flag
15797            flags |= PackageManager.DELETE_KEEP_DATA;
15798        }
15799
15800        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15801                outInfo, writeSettings, disabledPs.pkg);
15802        if (!ret) {
15803            return false;
15804        }
15805
15806        // writer
15807        synchronized (mPackages) {
15808            // Reinstate the old system package
15809            enableSystemPackageLPw(disabledPs.pkg);
15810            // Remove any native libraries from the upgraded package.
15811            removeNativeBinariesLI(deletedPs);
15812        }
15813
15814        // Install the system package
15815        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15816        int parseFlags = mDefParseFlags
15817                | PackageParser.PARSE_MUST_BE_APK
15818                | PackageParser.PARSE_IS_SYSTEM
15819                | PackageParser.PARSE_IS_SYSTEM_DIR;
15820        if (locationIsPrivileged(disabledPs.codePath)) {
15821            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15822        }
15823
15824        final PackageParser.Package newPkg;
15825        try {
15826            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15827        } catch (PackageManagerException e) {
15828            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15829                    + e.getMessage());
15830            return false;
15831        }
15832        try {
15833            // update shared libraries for the newly re-installed system package
15834            updateSharedLibrariesLPw(newPkg, null);
15835        } catch (PackageManagerException e) {
15836            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
15837        }
15838
15839        prepareAppDataAfterInstallLIF(newPkg);
15840
15841        // writer
15842        synchronized (mPackages) {
15843            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15844
15845            // Propagate the permissions state as we do not want to drop on the floor
15846            // runtime permissions. The update permissions method below will take
15847            // care of removing obsolete permissions and grant install permissions.
15848            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15849            updatePermissionsLPw(newPkg.packageName, newPkg,
15850                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15851
15852            if (applyUserRestrictions) {
15853                if (DEBUG_REMOVE) {
15854                    Slog.d(TAG, "Propagating install state across reinstall");
15855                }
15856                for (int userId : allUserHandles) {
15857                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15858                    if (DEBUG_REMOVE) {
15859                        Slog.d(TAG, "    user " + userId + " => " + installed);
15860                    }
15861                    ps.setInstalled(installed, userId);
15862
15863                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15864                }
15865                // Regardless of writeSettings we need to ensure that this restriction
15866                // state propagation is persisted
15867                mSettings.writeAllUsersPackageRestrictionsLPr();
15868            }
15869            // can downgrade to reader here
15870            if (writeSettings) {
15871                mSettings.writeLPr();
15872            }
15873        }
15874        return true;
15875    }
15876
15877    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15878            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15879            PackageRemovedInfo outInfo, boolean writeSettings,
15880            PackageParser.Package replacingPackage) {
15881        synchronized (mPackages) {
15882            if (outInfo != null) {
15883                outInfo.uid = ps.appId;
15884            }
15885
15886            if (outInfo != null && outInfo.removedChildPackages != null) {
15887                final int childCount = (ps.childPackageNames != null)
15888                        ? ps.childPackageNames.size() : 0;
15889                for (int i = 0; i < childCount; i++) {
15890                    String childPackageName = ps.childPackageNames.get(i);
15891                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15892                    if (childPs == null) {
15893                        return false;
15894                    }
15895                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15896                            childPackageName);
15897                    if (childInfo != null) {
15898                        childInfo.uid = childPs.appId;
15899                    }
15900                }
15901            }
15902        }
15903
15904        // Delete package data from internal structures and also remove data if flag is set
15905        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15906
15907        // Delete the child packages data
15908        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15909        for (int i = 0; i < childCount; i++) {
15910            PackageSetting childPs;
15911            synchronized (mPackages) {
15912                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15913            }
15914            if (childPs != null) {
15915                PackageRemovedInfo childOutInfo = (outInfo != null
15916                        && outInfo.removedChildPackages != null)
15917                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15918                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15919                        && (replacingPackage != null
15920                        && !replacingPackage.hasChildPackage(childPs.name))
15921                        ? flags & ~DELETE_KEEP_DATA : flags;
15922                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15923                        deleteFlags, writeSettings);
15924            }
15925        }
15926
15927        // Delete application code and resources only for parent packages
15928        if (ps.parentPackageName == null) {
15929            if (deleteCodeAndResources && (outInfo != null)) {
15930                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15931                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15932                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15933            }
15934        }
15935
15936        return true;
15937    }
15938
15939    @Override
15940    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15941            int userId) {
15942        mContext.enforceCallingOrSelfPermission(
15943                android.Manifest.permission.DELETE_PACKAGES, null);
15944        synchronized (mPackages) {
15945            PackageSetting ps = mSettings.mPackages.get(packageName);
15946            if (ps == null) {
15947                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15948                return false;
15949            }
15950            if (!ps.getInstalled(userId)) {
15951                // Can't block uninstall for an app that is not installed or enabled.
15952                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15953                return false;
15954            }
15955            ps.setBlockUninstall(blockUninstall, userId);
15956            mSettings.writePackageRestrictionsLPr(userId);
15957        }
15958        return true;
15959    }
15960
15961    @Override
15962    public boolean getBlockUninstallForUser(String packageName, int userId) {
15963        synchronized (mPackages) {
15964            PackageSetting ps = mSettings.mPackages.get(packageName);
15965            if (ps == null) {
15966                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15967                return false;
15968            }
15969            return ps.getBlockUninstall(userId);
15970        }
15971    }
15972
15973    @Override
15974    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15975        int callingUid = Binder.getCallingUid();
15976        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15977            throw new SecurityException(
15978                    "setRequiredForSystemUser can only be run by the system or root");
15979        }
15980        synchronized (mPackages) {
15981            PackageSetting ps = mSettings.mPackages.get(packageName);
15982            if (ps == null) {
15983                Log.w(TAG, "Package doesn't exist: " + packageName);
15984                return false;
15985            }
15986            if (systemUserApp) {
15987                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15988            } else {
15989                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15990            }
15991            mSettings.writeLPr();
15992        }
15993        return true;
15994    }
15995
15996    /*
15997     * This method handles package deletion in general
15998     */
15999    private boolean deletePackageLIF(String packageName, UserHandle user,
16000            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16001            PackageRemovedInfo outInfo, boolean writeSettings,
16002            PackageParser.Package replacingPackage) {
16003        if (packageName == null) {
16004            Slog.w(TAG, "Attempt to delete null packageName.");
16005            return false;
16006        }
16007
16008        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16009
16010        PackageSetting ps;
16011
16012        synchronized (mPackages) {
16013            ps = mSettings.mPackages.get(packageName);
16014            if (ps == null) {
16015                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16016                return false;
16017            }
16018
16019            if (ps.parentPackageName != null && (!isSystemApp(ps)
16020                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16021                if (DEBUG_REMOVE) {
16022                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16023                            + ((user == null) ? UserHandle.USER_ALL : user));
16024                }
16025                final int removedUserId = (user != null) ? user.getIdentifier()
16026                        : UserHandle.USER_ALL;
16027                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16028                    return false;
16029                }
16030                markPackageUninstalledForUserLPw(ps, user);
16031                scheduleWritePackageRestrictionsLocked(user);
16032                return true;
16033            }
16034        }
16035
16036        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16037                && user.getIdentifier() != UserHandle.USER_ALL)) {
16038            // The caller is asking that the package only be deleted for a single
16039            // user.  To do this, we just mark its uninstalled state and delete
16040            // its data. If this is a system app, we only allow this to happen if
16041            // they have set the special DELETE_SYSTEM_APP which requests different
16042            // semantics than normal for uninstalling system apps.
16043            markPackageUninstalledForUserLPw(ps, user);
16044
16045            if (!isSystemApp(ps)) {
16046                // Do not uninstall the APK if an app should be cached
16047                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16048                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16049                    // Other user still have this package installed, so all
16050                    // we need to do is clear this user's data and save that
16051                    // it is uninstalled.
16052                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16053                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16054                        return false;
16055                    }
16056                    scheduleWritePackageRestrictionsLocked(user);
16057                    return true;
16058                } else {
16059                    // We need to set it back to 'installed' so the uninstall
16060                    // broadcasts will be sent correctly.
16061                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16062                    ps.setInstalled(true, user.getIdentifier());
16063                }
16064            } else {
16065                // This is a system app, so we assume that the
16066                // other users still have this package installed, so all
16067                // we need to do is clear this user's data and save that
16068                // it is uninstalled.
16069                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16070                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16071                    return false;
16072                }
16073                scheduleWritePackageRestrictionsLocked(user);
16074                return true;
16075            }
16076        }
16077
16078        // If we are deleting a composite package for all users, keep track
16079        // of result for each child.
16080        if (ps.childPackageNames != null && outInfo != null) {
16081            synchronized (mPackages) {
16082                final int childCount = ps.childPackageNames.size();
16083                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16084                for (int i = 0; i < childCount; i++) {
16085                    String childPackageName = ps.childPackageNames.get(i);
16086                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16087                    childInfo.removedPackage = childPackageName;
16088                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16089                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16090                    if (childPs != null) {
16091                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16092                    }
16093                }
16094            }
16095        }
16096
16097        boolean ret = false;
16098        if (isSystemApp(ps)) {
16099            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16100            // When an updated system application is deleted we delete the existing resources
16101            // as well and fall back to existing code in system partition
16102            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16103        } else {
16104            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16105            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16106                    outInfo, writeSettings, replacingPackage);
16107        }
16108
16109        // Take a note whether we deleted the package for all users
16110        if (outInfo != null) {
16111            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16112            if (outInfo.removedChildPackages != null) {
16113                synchronized (mPackages) {
16114                    final int childCount = outInfo.removedChildPackages.size();
16115                    for (int i = 0; i < childCount; i++) {
16116                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16117                        if (childInfo != null) {
16118                            childInfo.removedForAllUsers = mPackages.get(
16119                                    childInfo.removedPackage) == null;
16120                        }
16121                    }
16122                }
16123            }
16124            // If we uninstalled an update to a system app there may be some
16125            // child packages that appeared as they are declared in the system
16126            // app but were not declared in the update.
16127            if (isSystemApp(ps)) {
16128                synchronized (mPackages) {
16129                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16130                    final int childCount = (updatedPs.childPackageNames != null)
16131                            ? updatedPs.childPackageNames.size() : 0;
16132                    for (int i = 0; i < childCount; i++) {
16133                        String childPackageName = updatedPs.childPackageNames.get(i);
16134                        if (outInfo.removedChildPackages == null
16135                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16136                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16137                            if (childPs == null) {
16138                                continue;
16139                            }
16140                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16141                            installRes.name = childPackageName;
16142                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16143                            installRes.pkg = mPackages.get(childPackageName);
16144                            installRes.uid = childPs.pkg.applicationInfo.uid;
16145                            if (outInfo.appearedChildPackages == null) {
16146                                outInfo.appearedChildPackages = new ArrayMap<>();
16147                            }
16148                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16149                        }
16150                    }
16151                }
16152            }
16153        }
16154
16155        return ret;
16156    }
16157
16158    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16159        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16160                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16161        for (int nextUserId : userIds) {
16162            if (DEBUG_REMOVE) {
16163                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16164            }
16165            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16166                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16167                    false /*hidden*/, false /*suspended*/, null, null, null,
16168                    false /*blockUninstall*/,
16169                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16170        }
16171    }
16172
16173    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16174            PackageRemovedInfo outInfo) {
16175        final PackageParser.Package pkg;
16176        synchronized (mPackages) {
16177            pkg = mPackages.get(ps.name);
16178        }
16179
16180        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16181                : new int[] {userId};
16182        for (int nextUserId : userIds) {
16183            if (DEBUG_REMOVE) {
16184                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16185                        + nextUserId);
16186            }
16187
16188            destroyAppDataLIF(pkg, userId,
16189                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16190            destroyAppProfilesLIF(pkg, userId);
16191            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16192            schedulePackageCleaning(ps.name, nextUserId, false);
16193            synchronized (mPackages) {
16194                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16195                    scheduleWritePackageRestrictionsLocked(nextUserId);
16196                }
16197                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16198            }
16199        }
16200
16201        if (outInfo != null) {
16202            outInfo.removedPackage = ps.name;
16203            outInfo.removedAppId = ps.appId;
16204            outInfo.removedUsers = userIds;
16205        }
16206
16207        return true;
16208    }
16209
16210    private final class ClearStorageConnection implements ServiceConnection {
16211        IMediaContainerService mContainerService;
16212
16213        @Override
16214        public void onServiceConnected(ComponentName name, IBinder service) {
16215            synchronized (this) {
16216                mContainerService = IMediaContainerService.Stub.asInterface(service);
16217                notifyAll();
16218            }
16219        }
16220
16221        @Override
16222        public void onServiceDisconnected(ComponentName name) {
16223        }
16224    }
16225
16226    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16227        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16228
16229        final boolean mounted;
16230        if (Environment.isExternalStorageEmulated()) {
16231            mounted = true;
16232        } else {
16233            final String status = Environment.getExternalStorageState();
16234
16235            mounted = status.equals(Environment.MEDIA_MOUNTED)
16236                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16237        }
16238
16239        if (!mounted) {
16240            return;
16241        }
16242
16243        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16244        int[] users;
16245        if (userId == UserHandle.USER_ALL) {
16246            users = sUserManager.getUserIds();
16247        } else {
16248            users = new int[] { userId };
16249        }
16250        final ClearStorageConnection conn = new ClearStorageConnection();
16251        if (mContext.bindServiceAsUser(
16252                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16253            try {
16254                for (int curUser : users) {
16255                    long timeout = SystemClock.uptimeMillis() + 5000;
16256                    synchronized (conn) {
16257                        long now;
16258                        while (conn.mContainerService == null &&
16259                                (now = SystemClock.uptimeMillis()) < timeout) {
16260                            try {
16261                                conn.wait(timeout - now);
16262                            } catch (InterruptedException e) {
16263                            }
16264                        }
16265                    }
16266                    if (conn.mContainerService == null) {
16267                        return;
16268                    }
16269
16270                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16271                    clearDirectory(conn.mContainerService,
16272                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16273                    if (allData) {
16274                        clearDirectory(conn.mContainerService,
16275                                userEnv.buildExternalStorageAppDataDirs(packageName));
16276                        clearDirectory(conn.mContainerService,
16277                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16278                    }
16279                }
16280            } finally {
16281                mContext.unbindService(conn);
16282            }
16283        }
16284    }
16285
16286    @Override
16287    public void clearApplicationProfileData(String packageName) {
16288        enforceSystemOrRoot("Only the system can clear all profile data");
16289
16290        final PackageParser.Package pkg;
16291        synchronized (mPackages) {
16292            pkg = mPackages.get(packageName);
16293        }
16294
16295        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16296            synchronized (mInstallLock) {
16297                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16298                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16299                        true /* removeBaseMarker */);
16300            }
16301        }
16302    }
16303
16304    @Override
16305    public void clearApplicationUserData(final String packageName,
16306            final IPackageDataObserver observer, final int userId) {
16307        mContext.enforceCallingOrSelfPermission(
16308                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16309
16310        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16311                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16312
16313        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16314            throw new SecurityException("Cannot clear data for a protected package: "
16315                    + packageName);
16316        }
16317        // Queue up an async operation since the package deletion may take a little while.
16318        mHandler.post(new Runnable() {
16319            public void run() {
16320                mHandler.removeCallbacks(this);
16321                final boolean succeeded;
16322                try (PackageFreezer freezer = freezePackage(packageName,
16323                        "clearApplicationUserData")) {
16324                    synchronized (mInstallLock) {
16325                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16326                    }
16327                    clearExternalStorageDataSync(packageName, userId, true);
16328                }
16329                if (succeeded) {
16330                    // invoke DeviceStorageMonitor's update method to clear any notifications
16331                    DeviceStorageMonitorInternal dsm = LocalServices
16332                            .getService(DeviceStorageMonitorInternal.class);
16333                    if (dsm != null) {
16334                        dsm.checkMemory();
16335                    }
16336                }
16337                if(observer != null) {
16338                    try {
16339                        observer.onRemoveCompleted(packageName, succeeded);
16340                    } catch (RemoteException e) {
16341                        Log.i(TAG, "Observer no longer exists.");
16342                    }
16343                } //end if observer
16344            } //end run
16345        });
16346    }
16347
16348    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16349        if (packageName == null) {
16350            Slog.w(TAG, "Attempt to delete null packageName.");
16351            return false;
16352        }
16353
16354        // Try finding details about the requested package
16355        PackageParser.Package pkg;
16356        synchronized (mPackages) {
16357            pkg = mPackages.get(packageName);
16358            if (pkg == null) {
16359                final PackageSetting ps = mSettings.mPackages.get(packageName);
16360                if (ps != null) {
16361                    pkg = ps.pkg;
16362                }
16363            }
16364
16365            if (pkg == null) {
16366                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16367                return false;
16368            }
16369
16370            PackageSetting ps = (PackageSetting) pkg.mExtras;
16371            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16372        }
16373
16374        clearAppDataLIF(pkg, userId,
16375                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16376
16377        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16378        removeKeystoreDataIfNeeded(userId, appId);
16379
16380        UserManagerInternal umInternal = getUserManagerInternal();
16381        final int flags;
16382        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16383            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16384        } else if (umInternal.isUserRunning(userId)) {
16385            flags = StorageManager.FLAG_STORAGE_DE;
16386        } else {
16387            flags = 0;
16388        }
16389        prepareAppDataContentsLIF(pkg, userId, flags);
16390
16391        return true;
16392    }
16393
16394    /**
16395     * Reverts user permission state changes (permissions and flags) in
16396     * all packages for a given user.
16397     *
16398     * @param userId The device user for which to do a reset.
16399     */
16400    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16401        final int packageCount = mPackages.size();
16402        for (int i = 0; i < packageCount; i++) {
16403            PackageParser.Package pkg = mPackages.valueAt(i);
16404            PackageSetting ps = (PackageSetting) pkg.mExtras;
16405            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16406        }
16407    }
16408
16409    private void resetNetworkPolicies(int userId) {
16410        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16411    }
16412
16413    /**
16414     * Reverts user permission state changes (permissions and flags).
16415     *
16416     * @param ps The package for which to reset.
16417     * @param userId The device user for which to do a reset.
16418     */
16419    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16420            final PackageSetting ps, final int userId) {
16421        if (ps.pkg == null) {
16422            return;
16423        }
16424
16425        // These are flags that can change base on user actions.
16426        final int userSettableMask = FLAG_PERMISSION_USER_SET
16427                | FLAG_PERMISSION_USER_FIXED
16428                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16429                | FLAG_PERMISSION_REVIEW_REQUIRED;
16430
16431        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16432                | FLAG_PERMISSION_POLICY_FIXED;
16433
16434        boolean writeInstallPermissions = false;
16435        boolean writeRuntimePermissions = false;
16436
16437        final int permissionCount = ps.pkg.requestedPermissions.size();
16438        for (int i = 0; i < permissionCount; i++) {
16439            String permission = ps.pkg.requestedPermissions.get(i);
16440
16441            BasePermission bp = mSettings.mPermissions.get(permission);
16442            if (bp == null) {
16443                continue;
16444            }
16445
16446            // If shared user we just reset the state to which only this app contributed.
16447            if (ps.sharedUser != null) {
16448                boolean used = false;
16449                final int packageCount = ps.sharedUser.packages.size();
16450                for (int j = 0; j < packageCount; j++) {
16451                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16452                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16453                            && pkg.pkg.requestedPermissions.contains(permission)) {
16454                        used = true;
16455                        break;
16456                    }
16457                }
16458                if (used) {
16459                    continue;
16460                }
16461            }
16462
16463            PermissionsState permissionsState = ps.getPermissionsState();
16464
16465            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16466
16467            // Always clear the user settable flags.
16468            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16469                    bp.name) != null;
16470            // If permission review is enabled and this is a legacy app, mark the
16471            // permission as requiring a review as this is the initial state.
16472            int flags = 0;
16473            if (Build.PERMISSIONS_REVIEW_REQUIRED
16474                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16475                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16476            }
16477            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16478                if (hasInstallState) {
16479                    writeInstallPermissions = true;
16480                } else {
16481                    writeRuntimePermissions = true;
16482                }
16483            }
16484
16485            // Below is only runtime permission handling.
16486            if (!bp.isRuntime()) {
16487                continue;
16488            }
16489
16490            // Never clobber system or policy.
16491            if ((oldFlags & policyOrSystemFlags) != 0) {
16492                continue;
16493            }
16494
16495            // If this permission was granted by default, make sure it is.
16496            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16497                if (permissionsState.grantRuntimePermission(bp, userId)
16498                        != PERMISSION_OPERATION_FAILURE) {
16499                    writeRuntimePermissions = true;
16500                }
16501            // If permission review is enabled the permissions for a legacy apps
16502            // are represented as constantly granted runtime ones, so don't revoke.
16503            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16504                // Otherwise, reset the permission.
16505                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16506                switch (revokeResult) {
16507                    case PERMISSION_OPERATION_SUCCESS:
16508                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16509                        writeRuntimePermissions = true;
16510                        final int appId = ps.appId;
16511                        mHandler.post(new Runnable() {
16512                            @Override
16513                            public void run() {
16514                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16515                            }
16516                        });
16517                    } break;
16518                }
16519            }
16520        }
16521
16522        // Synchronously write as we are taking permissions away.
16523        if (writeRuntimePermissions) {
16524            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16525        }
16526
16527        // Synchronously write as we are taking permissions away.
16528        if (writeInstallPermissions) {
16529            mSettings.writeLPr();
16530        }
16531    }
16532
16533    /**
16534     * Remove entries from the keystore daemon. Will only remove it if the
16535     * {@code appId} is valid.
16536     */
16537    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16538        if (appId < 0) {
16539            return;
16540        }
16541
16542        final KeyStore keyStore = KeyStore.getInstance();
16543        if (keyStore != null) {
16544            if (userId == UserHandle.USER_ALL) {
16545                for (final int individual : sUserManager.getUserIds()) {
16546                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16547                }
16548            } else {
16549                keyStore.clearUid(UserHandle.getUid(userId, appId));
16550            }
16551        } else {
16552            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16553        }
16554    }
16555
16556    @Override
16557    public void deleteApplicationCacheFiles(final String packageName,
16558            final IPackageDataObserver observer) {
16559        final int userId = UserHandle.getCallingUserId();
16560        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16561    }
16562
16563    @Override
16564    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16565            final IPackageDataObserver observer) {
16566        mContext.enforceCallingOrSelfPermission(
16567                android.Manifest.permission.DELETE_CACHE_FILES, null);
16568        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16569                /* requireFullPermission= */ true, /* checkShell= */ false,
16570                "delete application cache files");
16571
16572        final PackageParser.Package pkg;
16573        synchronized (mPackages) {
16574            pkg = mPackages.get(packageName);
16575        }
16576
16577        // Queue up an async operation since the package deletion may take a little while.
16578        mHandler.post(new Runnable() {
16579            public void run() {
16580                synchronized (mInstallLock) {
16581                    final int flags = StorageManager.FLAG_STORAGE_DE
16582                            | StorageManager.FLAG_STORAGE_CE;
16583                    // We're only clearing cache files, so we don't care if the
16584                    // app is unfrozen and still able to run
16585                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16586                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16587                }
16588                clearExternalStorageDataSync(packageName, userId, false);
16589                if (observer != null) {
16590                    try {
16591                        observer.onRemoveCompleted(packageName, true);
16592                    } catch (RemoteException e) {
16593                        Log.i(TAG, "Observer no longer exists.");
16594                    }
16595                }
16596            }
16597        });
16598    }
16599
16600    @Override
16601    public void getPackageSizeInfo(final String packageName, int userHandle,
16602            final IPackageStatsObserver observer) {
16603        mContext.enforceCallingOrSelfPermission(
16604                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16605        if (packageName == null) {
16606            throw new IllegalArgumentException("Attempt to get size of null packageName");
16607        }
16608
16609        PackageStats stats = new PackageStats(packageName, userHandle);
16610
16611        /*
16612         * Queue up an async operation since the package measurement may take a
16613         * little while.
16614         */
16615        Message msg = mHandler.obtainMessage(INIT_COPY);
16616        msg.obj = new MeasureParams(stats, observer);
16617        mHandler.sendMessage(msg);
16618    }
16619
16620    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16621        final PackageSetting ps;
16622        synchronized (mPackages) {
16623            ps = mSettings.mPackages.get(packageName);
16624            if (ps == null) {
16625                Slog.w(TAG, "Failed to find settings for " + packageName);
16626                return false;
16627            }
16628        }
16629        try {
16630            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16631                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16632                    ps.getCeDataInode(userId), ps.codePathString, stats);
16633        } catch (InstallerException e) {
16634            Slog.w(TAG, String.valueOf(e));
16635            return false;
16636        }
16637
16638        // For now, ignore code size of packages on system partition
16639        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16640            stats.codeSize = 0;
16641        }
16642
16643        return true;
16644    }
16645
16646    private int getUidTargetSdkVersionLockedLPr(int uid) {
16647        Object obj = mSettings.getUserIdLPr(uid);
16648        if (obj instanceof SharedUserSetting) {
16649            final SharedUserSetting sus = (SharedUserSetting) obj;
16650            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16651            final Iterator<PackageSetting> it = sus.packages.iterator();
16652            while (it.hasNext()) {
16653                final PackageSetting ps = it.next();
16654                if (ps.pkg != null) {
16655                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16656                    if (v < vers) vers = v;
16657                }
16658            }
16659            return vers;
16660        } else if (obj instanceof PackageSetting) {
16661            final PackageSetting ps = (PackageSetting) obj;
16662            if (ps.pkg != null) {
16663                return ps.pkg.applicationInfo.targetSdkVersion;
16664            }
16665        }
16666        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16667    }
16668
16669    @Override
16670    public void addPreferredActivity(IntentFilter filter, int match,
16671            ComponentName[] set, ComponentName activity, int userId) {
16672        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16673                "Adding preferred");
16674    }
16675
16676    private void addPreferredActivityInternal(IntentFilter filter, int match,
16677            ComponentName[] set, ComponentName activity, boolean always, int userId,
16678            String opname) {
16679        // writer
16680        int callingUid = Binder.getCallingUid();
16681        enforceCrossUserPermission(callingUid, userId,
16682                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16683        if (filter.countActions() == 0) {
16684            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16685            return;
16686        }
16687        synchronized (mPackages) {
16688            if (mContext.checkCallingOrSelfPermission(
16689                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16690                    != PackageManager.PERMISSION_GRANTED) {
16691                if (getUidTargetSdkVersionLockedLPr(callingUid)
16692                        < Build.VERSION_CODES.FROYO) {
16693                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16694                            + callingUid);
16695                    return;
16696                }
16697                mContext.enforceCallingOrSelfPermission(
16698                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16699            }
16700
16701            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16702            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16703                    + userId + ":");
16704            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16705            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16706            scheduleWritePackageRestrictionsLocked(userId);
16707            postPreferredActivityChangedBroadcast(userId);
16708        }
16709    }
16710
16711    private void postPreferredActivityChangedBroadcast(int userId) {
16712        mHandler.post(() -> {
16713            final IActivityManager am = ActivityManagerNative.getDefault();
16714            if (am == null) {
16715                return;
16716            }
16717
16718            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
16719            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
16720            try {
16721                am.broadcastIntent(null, intent, null, null,
16722                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
16723                        null, false, false, userId);
16724            } catch (RemoteException e) {
16725            }
16726        });
16727    }
16728
16729    @Override
16730    public void replacePreferredActivity(IntentFilter filter, int match,
16731            ComponentName[] set, ComponentName activity, int userId) {
16732        if (filter.countActions() != 1) {
16733            throw new IllegalArgumentException(
16734                    "replacePreferredActivity expects filter to have only 1 action.");
16735        }
16736        if (filter.countDataAuthorities() != 0
16737                || filter.countDataPaths() != 0
16738                || filter.countDataSchemes() > 1
16739                || filter.countDataTypes() != 0) {
16740            throw new IllegalArgumentException(
16741                    "replacePreferredActivity expects filter to have no data authorities, " +
16742                    "paths, or types; and at most one scheme.");
16743        }
16744
16745        final int callingUid = Binder.getCallingUid();
16746        enforceCrossUserPermission(callingUid, userId,
16747                true /* requireFullPermission */, false /* checkShell */,
16748                "replace preferred activity");
16749        synchronized (mPackages) {
16750            if (mContext.checkCallingOrSelfPermission(
16751                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16752                    != PackageManager.PERMISSION_GRANTED) {
16753                if (getUidTargetSdkVersionLockedLPr(callingUid)
16754                        < Build.VERSION_CODES.FROYO) {
16755                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16756                            + Binder.getCallingUid());
16757                    return;
16758                }
16759                mContext.enforceCallingOrSelfPermission(
16760                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16761            }
16762
16763            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16764            if (pir != null) {
16765                // Get all of the existing entries that exactly match this filter.
16766                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16767                if (existing != null && existing.size() == 1) {
16768                    PreferredActivity cur = existing.get(0);
16769                    if (DEBUG_PREFERRED) {
16770                        Slog.i(TAG, "Checking replace of preferred:");
16771                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16772                        if (!cur.mPref.mAlways) {
16773                            Slog.i(TAG, "  -- CUR; not mAlways!");
16774                        } else {
16775                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16776                            Slog.i(TAG, "  -- CUR: mSet="
16777                                    + Arrays.toString(cur.mPref.mSetComponents));
16778                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16779                            Slog.i(TAG, "  -- NEW: mMatch="
16780                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16781                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16782                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16783                        }
16784                    }
16785                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16786                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16787                            && cur.mPref.sameSet(set)) {
16788                        // Setting the preferred activity to what it happens to be already
16789                        if (DEBUG_PREFERRED) {
16790                            Slog.i(TAG, "Replacing with same preferred activity "
16791                                    + cur.mPref.mShortComponent + " for user "
16792                                    + userId + ":");
16793                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16794                        }
16795                        return;
16796                    }
16797                }
16798
16799                if (existing != null) {
16800                    if (DEBUG_PREFERRED) {
16801                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16802                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16803                    }
16804                    for (int i = 0; i < existing.size(); i++) {
16805                        PreferredActivity pa = existing.get(i);
16806                        if (DEBUG_PREFERRED) {
16807                            Slog.i(TAG, "Removing existing preferred activity "
16808                                    + pa.mPref.mComponent + ":");
16809                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16810                        }
16811                        pir.removeFilter(pa);
16812                    }
16813                }
16814            }
16815            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16816                    "Replacing preferred");
16817        }
16818    }
16819
16820    @Override
16821    public void clearPackagePreferredActivities(String packageName) {
16822        final int uid = Binder.getCallingUid();
16823        // writer
16824        synchronized (mPackages) {
16825            PackageParser.Package pkg = mPackages.get(packageName);
16826            if (pkg == null || pkg.applicationInfo.uid != uid) {
16827                if (mContext.checkCallingOrSelfPermission(
16828                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16829                        != PackageManager.PERMISSION_GRANTED) {
16830                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16831                            < Build.VERSION_CODES.FROYO) {
16832                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16833                                + Binder.getCallingUid());
16834                        return;
16835                    }
16836                    mContext.enforceCallingOrSelfPermission(
16837                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16838                }
16839            }
16840
16841            int user = UserHandle.getCallingUserId();
16842            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16843                scheduleWritePackageRestrictionsLocked(user);
16844            }
16845        }
16846    }
16847
16848    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16849    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16850        ArrayList<PreferredActivity> removed = null;
16851        boolean changed = false;
16852        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16853            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16854            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16855            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16856                continue;
16857            }
16858            Iterator<PreferredActivity> it = pir.filterIterator();
16859            while (it.hasNext()) {
16860                PreferredActivity pa = it.next();
16861                // Mark entry for removal only if it matches the package name
16862                // and the entry is of type "always".
16863                if (packageName == null ||
16864                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16865                                && pa.mPref.mAlways)) {
16866                    if (removed == null) {
16867                        removed = new ArrayList<PreferredActivity>();
16868                    }
16869                    removed.add(pa);
16870                }
16871            }
16872            if (removed != null) {
16873                for (int j=0; j<removed.size(); j++) {
16874                    PreferredActivity pa = removed.get(j);
16875                    pir.removeFilter(pa);
16876                }
16877                changed = true;
16878            }
16879        }
16880        if (changed) {
16881            postPreferredActivityChangedBroadcast(userId);
16882        }
16883        return changed;
16884    }
16885
16886    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16887    private void clearIntentFilterVerificationsLPw(int userId) {
16888        final int packageCount = mPackages.size();
16889        for (int i = 0; i < packageCount; i++) {
16890            PackageParser.Package pkg = mPackages.valueAt(i);
16891            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16892        }
16893    }
16894
16895    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16896    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16897        if (userId == UserHandle.USER_ALL) {
16898            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16899                    sUserManager.getUserIds())) {
16900                for (int oneUserId : sUserManager.getUserIds()) {
16901                    scheduleWritePackageRestrictionsLocked(oneUserId);
16902                }
16903            }
16904        } else {
16905            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16906                scheduleWritePackageRestrictionsLocked(userId);
16907            }
16908        }
16909    }
16910
16911    void clearDefaultBrowserIfNeeded(String packageName) {
16912        for (int oneUserId : sUserManager.getUserIds()) {
16913            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16914            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16915            if (packageName.equals(defaultBrowserPackageName)) {
16916                setDefaultBrowserPackageName(null, oneUserId);
16917            }
16918        }
16919    }
16920
16921    @Override
16922    public void resetApplicationPreferences(int userId) {
16923        mContext.enforceCallingOrSelfPermission(
16924                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16925        final long identity = Binder.clearCallingIdentity();
16926        // writer
16927        try {
16928            synchronized (mPackages) {
16929                clearPackagePreferredActivitiesLPw(null, userId);
16930                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16931                // TODO: We have to reset the default SMS and Phone. This requires
16932                // significant refactoring to keep all default apps in the package
16933                // manager (cleaner but more work) or have the services provide
16934                // callbacks to the package manager to request a default app reset.
16935                applyFactoryDefaultBrowserLPw(userId);
16936                clearIntentFilterVerificationsLPw(userId);
16937                primeDomainVerificationsLPw(userId);
16938                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16939                scheduleWritePackageRestrictionsLocked(userId);
16940            }
16941            resetNetworkPolicies(userId);
16942        } finally {
16943            Binder.restoreCallingIdentity(identity);
16944        }
16945    }
16946
16947    @Override
16948    public int getPreferredActivities(List<IntentFilter> outFilters,
16949            List<ComponentName> outActivities, String packageName) {
16950
16951        int num = 0;
16952        final int userId = UserHandle.getCallingUserId();
16953        // reader
16954        synchronized (mPackages) {
16955            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16956            if (pir != null) {
16957                final Iterator<PreferredActivity> it = pir.filterIterator();
16958                while (it.hasNext()) {
16959                    final PreferredActivity pa = it.next();
16960                    if (packageName == null
16961                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16962                                    && pa.mPref.mAlways)) {
16963                        if (outFilters != null) {
16964                            outFilters.add(new IntentFilter(pa));
16965                        }
16966                        if (outActivities != null) {
16967                            outActivities.add(pa.mPref.mComponent);
16968                        }
16969                    }
16970                }
16971            }
16972        }
16973
16974        return num;
16975    }
16976
16977    @Override
16978    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16979            int userId) {
16980        int callingUid = Binder.getCallingUid();
16981        if (callingUid != Process.SYSTEM_UID) {
16982            throw new SecurityException(
16983                    "addPersistentPreferredActivity can only be run by the system");
16984        }
16985        if (filter.countActions() == 0) {
16986            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16987            return;
16988        }
16989        synchronized (mPackages) {
16990            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16991                    ":");
16992            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16993            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16994                    new PersistentPreferredActivity(filter, activity));
16995            scheduleWritePackageRestrictionsLocked(userId);
16996            postPreferredActivityChangedBroadcast(userId);
16997        }
16998    }
16999
17000    @Override
17001    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17002        int callingUid = Binder.getCallingUid();
17003        if (callingUid != Process.SYSTEM_UID) {
17004            throw new SecurityException(
17005                    "clearPackagePersistentPreferredActivities can only be run by the system");
17006        }
17007        ArrayList<PersistentPreferredActivity> removed = null;
17008        boolean changed = false;
17009        synchronized (mPackages) {
17010            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17011                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17012                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17013                        .valueAt(i);
17014                if (userId != thisUserId) {
17015                    continue;
17016                }
17017                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17018                while (it.hasNext()) {
17019                    PersistentPreferredActivity ppa = it.next();
17020                    // Mark entry for removal only if it matches the package name.
17021                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17022                        if (removed == null) {
17023                            removed = new ArrayList<PersistentPreferredActivity>();
17024                        }
17025                        removed.add(ppa);
17026                    }
17027                }
17028                if (removed != null) {
17029                    for (int j=0; j<removed.size(); j++) {
17030                        PersistentPreferredActivity ppa = removed.get(j);
17031                        ppir.removeFilter(ppa);
17032                    }
17033                    changed = true;
17034                }
17035            }
17036
17037            if (changed) {
17038                scheduleWritePackageRestrictionsLocked(userId);
17039                postPreferredActivityChangedBroadcast(userId);
17040            }
17041        }
17042    }
17043
17044    /**
17045     * Common machinery for picking apart a restored XML blob and passing
17046     * it to a caller-supplied functor to be applied to the running system.
17047     */
17048    private void restoreFromXml(XmlPullParser parser, int userId,
17049            String expectedStartTag, BlobXmlRestorer functor)
17050            throws IOException, XmlPullParserException {
17051        int type;
17052        while ((type = parser.next()) != XmlPullParser.START_TAG
17053                && type != XmlPullParser.END_DOCUMENT) {
17054        }
17055        if (type != XmlPullParser.START_TAG) {
17056            // oops didn't find a start tag?!
17057            if (DEBUG_BACKUP) {
17058                Slog.e(TAG, "Didn't find start tag during restore");
17059            }
17060            return;
17061        }
17062Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17063        // this is supposed to be TAG_PREFERRED_BACKUP
17064        if (!expectedStartTag.equals(parser.getName())) {
17065            if (DEBUG_BACKUP) {
17066                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17067            }
17068            return;
17069        }
17070
17071        // skip interfering stuff, then we're aligned with the backing implementation
17072        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17073Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17074        functor.apply(parser, userId);
17075    }
17076
17077    private interface BlobXmlRestorer {
17078        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17079    }
17080
17081    /**
17082     * Non-Binder method, support for the backup/restore mechanism: write the
17083     * full set of preferred activities in its canonical XML format.  Returns the
17084     * XML output as a byte array, or null if there is none.
17085     */
17086    @Override
17087    public byte[] getPreferredActivityBackup(int userId) {
17088        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17089            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17090        }
17091
17092        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17093        try {
17094            final XmlSerializer serializer = new FastXmlSerializer();
17095            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17096            serializer.startDocument(null, true);
17097            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17098
17099            synchronized (mPackages) {
17100                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17101            }
17102
17103            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17104            serializer.endDocument();
17105            serializer.flush();
17106        } catch (Exception e) {
17107            if (DEBUG_BACKUP) {
17108                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17109            }
17110            return null;
17111        }
17112
17113        return dataStream.toByteArray();
17114    }
17115
17116    @Override
17117    public void restorePreferredActivities(byte[] backup, int userId) {
17118        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17119            throw new SecurityException("Only the system may call restorePreferredActivities()");
17120        }
17121
17122        try {
17123            final XmlPullParser parser = Xml.newPullParser();
17124            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17125            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17126                    new BlobXmlRestorer() {
17127                        @Override
17128                        public void apply(XmlPullParser parser, int userId)
17129                                throws XmlPullParserException, IOException {
17130                            synchronized (mPackages) {
17131                                mSettings.readPreferredActivitiesLPw(parser, userId);
17132                            }
17133                        }
17134                    } );
17135        } catch (Exception e) {
17136            if (DEBUG_BACKUP) {
17137                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17138            }
17139        }
17140    }
17141
17142    /**
17143     * Non-Binder method, support for the backup/restore mechanism: write the
17144     * default browser (etc) settings in its canonical XML format.  Returns the default
17145     * browser XML representation as a byte array, or null if there is none.
17146     */
17147    @Override
17148    public byte[] getDefaultAppsBackup(int userId) {
17149        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17150            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17151        }
17152
17153        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17154        try {
17155            final XmlSerializer serializer = new FastXmlSerializer();
17156            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17157            serializer.startDocument(null, true);
17158            serializer.startTag(null, TAG_DEFAULT_APPS);
17159
17160            synchronized (mPackages) {
17161                mSettings.writeDefaultAppsLPr(serializer, userId);
17162            }
17163
17164            serializer.endTag(null, TAG_DEFAULT_APPS);
17165            serializer.endDocument();
17166            serializer.flush();
17167        } catch (Exception e) {
17168            if (DEBUG_BACKUP) {
17169                Slog.e(TAG, "Unable to write default apps for backup", e);
17170            }
17171            return null;
17172        }
17173
17174        return dataStream.toByteArray();
17175    }
17176
17177    @Override
17178    public void restoreDefaultApps(byte[] backup, int userId) {
17179        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17180            throw new SecurityException("Only the system may call restoreDefaultApps()");
17181        }
17182
17183        try {
17184            final XmlPullParser parser = Xml.newPullParser();
17185            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17186            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17187                    new BlobXmlRestorer() {
17188                        @Override
17189                        public void apply(XmlPullParser parser, int userId)
17190                                throws XmlPullParserException, IOException {
17191                            synchronized (mPackages) {
17192                                mSettings.readDefaultAppsLPw(parser, userId);
17193                            }
17194                        }
17195                    } );
17196        } catch (Exception e) {
17197            if (DEBUG_BACKUP) {
17198                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17199            }
17200        }
17201    }
17202
17203    @Override
17204    public byte[] getIntentFilterVerificationBackup(int userId) {
17205        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17206            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17207        }
17208
17209        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17210        try {
17211            final XmlSerializer serializer = new FastXmlSerializer();
17212            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17213            serializer.startDocument(null, true);
17214            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17215
17216            synchronized (mPackages) {
17217                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17218            }
17219
17220            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17221            serializer.endDocument();
17222            serializer.flush();
17223        } catch (Exception e) {
17224            if (DEBUG_BACKUP) {
17225                Slog.e(TAG, "Unable to write default apps for backup", e);
17226            }
17227            return null;
17228        }
17229
17230        return dataStream.toByteArray();
17231    }
17232
17233    @Override
17234    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17235        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17236            throw new SecurityException("Only the system may call restorePreferredActivities()");
17237        }
17238
17239        try {
17240            final XmlPullParser parser = Xml.newPullParser();
17241            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17242            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17243                    new BlobXmlRestorer() {
17244                        @Override
17245                        public void apply(XmlPullParser parser, int userId)
17246                                throws XmlPullParserException, IOException {
17247                            synchronized (mPackages) {
17248                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17249                                mSettings.writeLPr();
17250                            }
17251                        }
17252                    } );
17253        } catch (Exception e) {
17254            if (DEBUG_BACKUP) {
17255                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17256            }
17257        }
17258    }
17259
17260    @Override
17261    public byte[] getPermissionGrantBackup(int userId) {
17262        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17263            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17264        }
17265
17266        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17267        try {
17268            final XmlSerializer serializer = new FastXmlSerializer();
17269            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17270            serializer.startDocument(null, true);
17271            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17272
17273            synchronized (mPackages) {
17274                serializeRuntimePermissionGrantsLPr(serializer, userId);
17275            }
17276
17277            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17278            serializer.endDocument();
17279            serializer.flush();
17280        } catch (Exception e) {
17281            if (DEBUG_BACKUP) {
17282                Slog.e(TAG, "Unable to write default apps for backup", e);
17283            }
17284            return null;
17285        }
17286
17287        return dataStream.toByteArray();
17288    }
17289
17290    @Override
17291    public void restorePermissionGrants(byte[] backup, int userId) {
17292        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17293            throw new SecurityException("Only the system may call restorePermissionGrants()");
17294        }
17295
17296        try {
17297            final XmlPullParser parser = Xml.newPullParser();
17298            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17299            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17300                    new BlobXmlRestorer() {
17301                        @Override
17302                        public void apply(XmlPullParser parser, int userId)
17303                                throws XmlPullParserException, IOException {
17304                            synchronized (mPackages) {
17305                                processRestoredPermissionGrantsLPr(parser, userId);
17306                            }
17307                        }
17308                    } );
17309        } catch (Exception e) {
17310            if (DEBUG_BACKUP) {
17311                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17312            }
17313        }
17314    }
17315
17316    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17317            throws IOException {
17318        serializer.startTag(null, TAG_ALL_GRANTS);
17319
17320        final int N = mSettings.mPackages.size();
17321        for (int i = 0; i < N; i++) {
17322            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17323            boolean pkgGrantsKnown = false;
17324
17325            PermissionsState packagePerms = ps.getPermissionsState();
17326
17327            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17328                final int grantFlags = state.getFlags();
17329                // only look at grants that are not system/policy fixed
17330                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17331                    final boolean isGranted = state.isGranted();
17332                    // And only back up the user-twiddled state bits
17333                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17334                        final String packageName = mSettings.mPackages.keyAt(i);
17335                        if (!pkgGrantsKnown) {
17336                            serializer.startTag(null, TAG_GRANT);
17337                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17338                            pkgGrantsKnown = true;
17339                        }
17340
17341                        final boolean userSet =
17342                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17343                        final boolean userFixed =
17344                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17345                        final boolean revoke =
17346                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17347
17348                        serializer.startTag(null, TAG_PERMISSION);
17349                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17350                        if (isGranted) {
17351                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17352                        }
17353                        if (userSet) {
17354                            serializer.attribute(null, ATTR_USER_SET, "true");
17355                        }
17356                        if (userFixed) {
17357                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17358                        }
17359                        if (revoke) {
17360                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17361                        }
17362                        serializer.endTag(null, TAG_PERMISSION);
17363                    }
17364                }
17365            }
17366
17367            if (pkgGrantsKnown) {
17368                serializer.endTag(null, TAG_GRANT);
17369            }
17370        }
17371
17372        serializer.endTag(null, TAG_ALL_GRANTS);
17373    }
17374
17375    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17376            throws XmlPullParserException, IOException {
17377        String pkgName = null;
17378        int outerDepth = parser.getDepth();
17379        int type;
17380        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17381                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17382            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17383                continue;
17384            }
17385
17386            final String tagName = parser.getName();
17387            if (tagName.equals(TAG_GRANT)) {
17388                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17389                if (DEBUG_BACKUP) {
17390                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17391                }
17392            } else if (tagName.equals(TAG_PERMISSION)) {
17393
17394                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17395                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17396
17397                int newFlagSet = 0;
17398                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17399                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17400                }
17401                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17402                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17403                }
17404                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17405                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17406                }
17407                if (DEBUG_BACKUP) {
17408                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17409                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17410                }
17411                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17412                if (ps != null) {
17413                    // Already installed so we apply the grant immediately
17414                    if (DEBUG_BACKUP) {
17415                        Slog.v(TAG, "        + already installed; applying");
17416                    }
17417                    PermissionsState perms = ps.getPermissionsState();
17418                    BasePermission bp = mSettings.mPermissions.get(permName);
17419                    if (bp != null) {
17420                        if (isGranted) {
17421                            perms.grantRuntimePermission(bp, userId);
17422                        }
17423                        if (newFlagSet != 0) {
17424                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17425                        }
17426                    }
17427                } else {
17428                    // Need to wait for post-restore install to apply the grant
17429                    if (DEBUG_BACKUP) {
17430                        Slog.v(TAG, "        - not yet installed; saving for later");
17431                    }
17432                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17433                            isGranted, newFlagSet, userId);
17434                }
17435            } else {
17436                PackageManagerService.reportSettingsProblem(Log.WARN,
17437                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17438                XmlUtils.skipCurrentTag(parser);
17439            }
17440        }
17441
17442        scheduleWriteSettingsLocked();
17443        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17444    }
17445
17446    @Override
17447    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17448            int sourceUserId, int targetUserId, int flags) {
17449        mContext.enforceCallingOrSelfPermission(
17450                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17451        int callingUid = Binder.getCallingUid();
17452        enforceOwnerRights(ownerPackage, callingUid);
17453        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17454        if (intentFilter.countActions() == 0) {
17455            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17456            return;
17457        }
17458        synchronized (mPackages) {
17459            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17460                    ownerPackage, targetUserId, flags);
17461            CrossProfileIntentResolver resolver =
17462                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17463            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17464            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17465            if (existing != null) {
17466                int size = existing.size();
17467                for (int i = 0; i < size; i++) {
17468                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17469                        return;
17470                    }
17471                }
17472            }
17473            resolver.addFilter(newFilter);
17474            scheduleWritePackageRestrictionsLocked(sourceUserId);
17475        }
17476    }
17477
17478    @Override
17479    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17480        mContext.enforceCallingOrSelfPermission(
17481                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17482        int callingUid = Binder.getCallingUid();
17483        enforceOwnerRights(ownerPackage, callingUid);
17484        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17485        synchronized (mPackages) {
17486            CrossProfileIntentResolver resolver =
17487                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17488            ArraySet<CrossProfileIntentFilter> set =
17489                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17490            for (CrossProfileIntentFilter filter : set) {
17491                if (filter.getOwnerPackage().equals(ownerPackage)) {
17492                    resolver.removeFilter(filter);
17493                }
17494            }
17495            scheduleWritePackageRestrictionsLocked(sourceUserId);
17496        }
17497    }
17498
17499    // Enforcing that callingUid is owning pkg on userId
17500    private void enforceOwnerRights(String pkg, int callingUid) {
17501        // The system owns everything.
17502        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17503            return;
17504        }
17505        int callingUserId = UserHandle.getUserId(callingUid);
17506        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17507        if (pi == null) {
17508            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17509                    + callingUserId);
17510        }
17511        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17512            throw new SecurityException("Calling uid " + callingUid
17513                    + " does not own package " + pkg);
17514        }
17515    }
17516
17517    @Override
17518    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17519        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17520    }
17521
17522    private Intent getHomeIntent() {
17523        Intent intent = new Intent(Intent.ACTION_MAIN);
17524        intent.addCategory(Intent.CATEGORY_HOME);
17525        intent.addCategory(Intent.CATEGORY_DEFAULT);
17526        return intent;
17527    }
17528
17529    private IntentFilter getHomeFilter() {
17530        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17531        filter.addCategory(Intent.CATEGORY_HOME);
17532        filter.addCategory(Intent.CATEGORY_DEFAULT);
17533        return filter;
17534    }
17535
17536    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17537            int userId) {
17538        Intent intent  = getHomeIntent();
17539        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17540                PackageManager.GET_META_DATA, userId);
17541        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17542                true, false, false, userId);
17543
17544        allHomeCandidates.clear();
17545        if (list != null) {
17546            for (ResolveInfo ri : list) {
17547                allHomeCandidates.add(ri);
17548            }
17549        }
17550        return (preferred == null || preferred.activityInfo == null)
17551                ? null
17552                : new ComponentName(preferred.activityInfo.packageName,
17553                        preferred.activityInfo.name);
17554    }
17555
17556    @Override
17557    public void setHomeActivity(ComponentName comp, int userId) {
17558        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17559        getHomeActivitiesAsUser(homeActivities, userId);
17560
17561        boolean found = false;
17562
17563        final int size = homeActivities.size();
17564        final ComponentName[] set = new ComponentName[size];
17565        for (int i = 0; i < size; i++) {
17566            final ResolveInfo candidate = homeActivities.get(i);
17567            final ActivityInfo info = candidate.activityInfo;
17568            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17569            set[i] = activityName;
17570            if (!found && activityName.equals(comp)) {
17571                found = true;
17572            }
17573        }
17574        if (!found) {
17575            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17576                    + userId);
17577        }
17578        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17579                set, comp, userId);
17580    }
17581
17582    private @Nullable String getSetupWizardPackageName() {
17583        final Intent intent = new Intent(Intent.ACTION_MAIN);
17584        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17585
17586        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17587                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17588                        | MATCH_DISABLED_COMPONENTS,
17589                UserHandle.myUserId());
17590        if (matches.size() == 1) {
17591            return matches.get(0).getComponentInfo().packageName;
17592        } else {
17593            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17594                    + ": matches=" + matches);
17595            return null;
17596        }
17597    }
17598
17599    @Override
17600    public void setApplicationEnabledSetting(String appPackageName,
17601            int newState, int flags, int userId, String callingPackage) {
17602        if (!sUserManager.exists(userId)) return;
17603        if (callingPackage == null) {
17604            callingPackage = Integer.toString(Binder.getCallingUid());
17605        }
17606        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17607    }
17608
17609    @Override
17610    public void setComponentEnabledSetting(ComponentName componentName,
17611            int newState, int flags, int userId) {
17612        if (!sUserManager.exists(userId)) return;
17613        setEnabledSetting(componentName.getPackageName(),
17614                componentName.getClassName(), newState, flags, userId, null);
17615    }
17616
17617    private void setEnabledSetting(final String packageName, String className, int newState,
17618            final int flags, int userId, String callingPackage) {
17619        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17620              || newState == COMPONENT_ENABLED_STATE_ENABLED
17621              || newState == COMPONENT_ENABLED_STATE_DISABLED
17622              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17623              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17624            throw new IllegalArgumentException("Invalid new component state: "
17625                    + newState);
17626        }
17627        PackageSetting pkgSetting;
17628        final int uid = Binder.getCallingUid();
17629        final int permission;
17630        if (uid == Process.SYSTEM_UID) {
17631            permission = PackageManager.PERMISSION_GRANTED;
17632        } else {
17633            permission = mContext.checkCallingOrSelfPermission(
17634                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17635        }
17636        enforceCrossUserPermission(uid, userId,
17637                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17638        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17639        boolean sendNow = false;
17640        boolean isApp = (className == null);
17641        String componentName = isApp ? packageName : className;
17642        int packageUid = -1;
17643        ArrayList<String> components;
17644
17645        // writer
17646        synchronized (mPackages) {
17647            pkgSetting = mSettings.mPackages.get(packageName);
17648            if (pkgSetting == null) {
17649                if (className == null) {
17650                    throw new IllegalArgumentException("Unknown package: " + packageName);
17651                }
17652                throw new IllegalArgumentException(
17653                        "Unknown component: " + packageName + "/" + className);
17654            }
17655        }
17656
17657        // Limit who can change which apps
17658        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17659            // Don't allow apps that don't have permission to modify other apps
17660            if (!allowedByPermission) {
17661                throw new SecurityException(
17662                        "Permission Denial: attempt to change component state from pid="
17663                        + Binder.getCallingPid()
17664                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17665            }
17666            // Don't allow changing protected packages.
17667            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17668                throw new SecurityException("Cannot disable a protected package: " + packageName);
17669            }
17670        }
17671
17672        synchronized (mPackages) {
17673            if (uid == Process.SHELL_UID) {
17674                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17675                int oldState = pkgSetting.getEnabled(userId);
17676                if (className == null
17677                    &&
17678                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17679                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17680                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17681                    &&
17682                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17683                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17684                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17685                    // ok
17686                } else {
17687                    throw new SecurityException(
17688                            "Shell cannot change component state for " + packageName + "/"
17689                            + className + " to " + newState);
17690                }
17691            }
17692            if (className == null) {
17693                // We're dealing with an application/package level state change
17694                if (pkgSetting.getEnabled(userId) == newState) {
17695                    // Nothing to do
17696                    return;
17697                }
17698                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17699                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17700                    // Don't care about who enables an app.
17701                    callingPackage = null;
17702                }
17703                pkgSetting.setEnabled(newState, userId, callingPackage);
17704                // pkgSetting.pkg.mSetEnabled = newState;
17705            } else {
17706                // We're dealing with a component level state change
17707                // First, verify that this is a valid class name.
17708                PackageParser.Package pkg = pkgSetting.pkg;
17709                if (pkg == null || !pkg.hasComponentClassName(className)) {
17710                    if (pkg != null &&
17711                            pkg.applicationInfo.targetSdkVersion >=
17712                                    Build.VERSION_CODES.JELLY_BEAN) {
17713                        throw new IllegalArgumentException("Component class " + className
17714                                + " does not exist in " + packageName);
17715                    } else {
17716                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17717                                + className + " does not exist in " + packageName);
17718                    }
17719                }
17720                switch (newState) {
17721                case COMPONENT_ENABLED_STATE_ENABLED:
17722                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17723                        return;
17724                    }
17725                    break;
17726                case COMPONENT_ENABLED_STATE_DISABLED:
17727                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17728                        return;
17729                    }
17730                    break;
17731                case COMPONENT_ENABLED_STATE_DEFAULT:
17732                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17733                        return;
17734                    }
17735                    break;
17736                default:
17737                    Slog.e(TAG, "Invalid new component state: " + newState);
17738                    return;
17739                }
17740            }
17741            scheduleWritePackageRestrictionsLocked(userId);
17742            components = mPendingBroadcasts.get(userId, packageName);
17743            final boolean newPackage = components == null;
17744            if (newPackage) {
17745                components = new ArrayList<String>();
17746            }
17747            if (!components.contains(componentName)) {
17748                components.add(componentName);
17749            }
17750            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17751                sendNow = true;
17752                // Purge entry from pending broadcast list if another one exists already
17753                // since we are sending one right away.
17754                mPendingBroadcasts.remove(userId, packageName);
17755            } else {
17756                if (newPackage) {
17757                    mPendingBroadcasts.put(userId, packageName, components);
17758                }
17759                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17760                    // Schedule a message
17761                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17762                }
17763            }
17764        }
17765
17766        long callingId = Binder.clearCallingIdentity();
17767        try {
17768            if (sendNow) {
17769                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17770                sendPackageChangedBroadcast(packageName,
17771                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17772            }
17773        } finally {
17774            Binder.restoreCallingIdentity(callingId);
17775        }
17776    }
17777
17778    @Override
17779    public void flushPackageRestrictionsAsUser(int userId) {
17780        if (!sUserManager.exists(userId)) {
17781            return;
17782        }
17783        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17784                false /* checkShell */, "flushPackageRestrictions");
17785        synchronized (mPackages) {
17786            mSettings.writePackageRestrictionsLPr(userId);
17787            mDirtyUsers.remove(userId);
17788            if (mDirtyUsers.isEmpty()) {
17789                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17790            }
17791        }
17792    }
17793
17794    private void sendPackageChangedBroadcast(String packageName,
17795            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17796        if (DEBUG_INSTALL)
17797            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17798                    + componentNames);
17799        Bundle extras = new Bundle(4);
17800        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17801        String nameList[] = new String[componentNames.size()];
17802        componentNames.toArray(nameList);
17803        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17804        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17805        extras.putInt(Intent.EXTRA_UID, packageUid);
17806        // If this is not reporting a change of the overall package, then only send it
17807        // to registered receivers.  We don't want to launch a swath of apps for every
17808        // little component state change.
17809        final int flags = !componentNames.contains(packageName)
17810                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17811        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17812                new int[] {UserHandle.getUserId(packageUid)});
17813    }
17814
17815    @Override
17816    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17817        if (!sUserManager.exists(userId)) return;
17818        final int uid = Binder.getCallingUid();
17819        final int permission = mContext.checkCallingOrSelfPermission(
17820                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17821        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17822        enforceCrossUserPermission(uid, userId,
17823                true /* requireFullPermission */, true /* checkShell */, "stop package");
17824        // writer
17825        synchronized (mPackages) {
17826            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17827                    allowedByPermission, uid, userId)) {
17828                scheduleWritePackageRestrictionsLocked(userId);
17829            }
17830        }
17831    }
17832
17833    @Override
17834    public String getInstallerPackageName(String packageName) {
17835        // reader
17836        synchronized (mPackages) {
17837            return mSettings.getInstallerPackageNameLPr(packageName);
17838        }
17839    }
17840
17841    public boolean isOrphaned(String packageName) {
17842        // reader
17843        synchronized (mPackages) {
17844            return mSettings.isOrphaned(packageName);
17845        }
17846    }
17847
17848    @Override
17849    public int getApplicationEnabledSetting(String packageName, int userId) {
17850        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17851        int uid = Binder.getCallingUid();
17852        enforceCrossUserPermission(uid, userId,
17853                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17854        // reader
17855        synchronized (mPackages) {
17856            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17857        }
17858    }
17859
17860    @Override
17861    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17862        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17863        int uid = Binder.getCallingUid();
17864        enforceCrossUserPermission(uid, userId,
17865                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17866        // reader
17867        synchronized (mPackages) {
17868            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17869        }
17870    }
17871
17872    @Override
17873    public void enterSafeMode() {
17874        enforceSystemOrRoot("Only the system can request entering safe mode");
17875
17876        if (!mSystemReady) {
17877            mSafeMode = true;
17878        }
17879    }
17880
17881    @Override
17882    public void systemReady() {
17883        mSystemReady = true;
17884
17885        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
17886        // disabled after already being started.
17887        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
17888                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
17889
17890        // Read the compatibilty setting when the system is ready.
17891        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17892                mContext.getContentResolver(),
17893                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17894        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17895        if (DEBUG_SETTINGS) {
17896            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17897        }
17898
17899        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17900
17901        synchronized (mPackages) {
17902            // Verify that all of the preferred activity components actually
17903            // exist.  It is possible for applications to be updated and at
17904            // that point remove a previously declared activity component that
17905            // had been set as a preferred activity.  We try to clean this up
17906            // the next time we encounter that preferred activity, but it is
17907            // possible for the user flow to never be able to return to that
17908            // situation so here we do a sanity check to make sure we haven't
17909            // left any junk around.
17910            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17911            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17912                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17913                removed.clear();
17914                for (PreferredActivity pa : pir.filterSet()) {
17915                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17916                        removed.add(pa);
17917                    }
17918                }
17919                if (removed.size() > 0) {
17920                    for (int r=0; r<removed.size(); r++) {
17921                        PreferredActivity pa = removed.get(r);
17922                        Slog.w(TAG, "Removing dangling preferred activity: "
17923                                + pa.mPref.mComponent);
17924                        pir.removeFilter(pa);
17925                    }
17926                    mSettings.writePackageRestrictionsLPr(
17927                            mSettings.mPreferredActivities.keyAt(i));
17928                }
17929            }
17930
17931            for (int userId : UserManagerService.getInstance().getUserIds()) {
17932                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17933                    grantPermissionsUserIds = ArrayUtils.appendInt(
17934                            grantPermissionsUserIds, userId);
17935                }
17936            }
17937        }
17938        sUserManager.systemReady();
17939
17940        // If we upgraded grant all default permissions before kicking off.
17941        for (int userId : grantPermissionsUserIds) {
17942            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17943        }
17944
17945        // Kick off any messages waiting for system ready
17946        if (mPostSystemReadyMessages != null) {
17947            for (Message msg : mPostSystemReadyMessages) {
17948                msg.sendToTarget();
17949            }
17950            mPostSystemReadyMessages = null;
17951        }
17952
17953        // Watch for external volumes that come and go over time
17954        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17955        storage.registerListener(mStorageListener);
17956
17957        mInstallerService.systemReady();
17958        mPackageDexOptimizer.systemReady();
17959
17960        MountServiceInternal mountServiceInternal = LocalServices.getService(
17961                MountServiceInternal.class);
17962        mountServiceInternal.addExternalStoragePolicy(
17963                new MountServiceInternal.ExternalStorageMountPolicy() {
17964            @Override
17965            public int getMountMode(int uid, String packageName) {
17966                if (Process.isIsolated(uid)) {
17967                    return Zygote.MOUNT_EXTERNAL_NONE;
17968                }
17969                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17970                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17971                }
17972                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17973                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17974                }
17975                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17976                    return Zygote.MOUNT_EXTERNAL_READ;
17977                }
17978                return Zygote.MOUNT_EXTERNAL_WRITE;
17979            }
17980
17981            @Override
17982            public boolean hasExternalStorage(int uid, String packageName) {
17983                return true;
17984            }
17985        });
17986
17987        // Now that we're mostly running, clean up stale users and apps
17988        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
17989        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
17990    }
17991
17992    @Override
17993    public boolean isSafeMode() {
17994        return mSafeMode;
17995    }
17996
17997    @Override
17998    public boolean hasSystemUidErrors() {
17999        return mHasSystemUidErrors;
18000    }
18001
18002    static String arrayToString(int[] array) {
18003        StringBuffer buf = new StringBuffer(128);
18004        buf.append('[');
18005        if (array != null) {
18006            for (int i=0; i<array.length; i++) {
18007                if (i > 0) buf.append(", ");
18008                buf.append(array[i]);
18009            }
18010        }
18011        buf.append(']');
18012        return buf.toString();
18013    }
18014
18015    static class DumpState {
18016        public static final int DUMP_LIBS = 1 << 0;
18017        public static final int DUMP_FEATURES = 1 << 1;
18018        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18019        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18020        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18021        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18022        public static final int DUMP_PERMISSIONS = 1 << 6;
18023        public static final int DUMP_PACKAGES = 1 << 7;
18024        public static final int DUMP_SHARED_USERS = 1 << 8;
18025        public static final int DUMP_MESSAGES = 1 << 9;
18026        public static final int DUMP_PROVIDERS = 1 << 10;
18027        public static final int DUMP_VERIFIERS = 1 << 11;
18028        public static final int DUMP_PREFERRED = 1 << 12;
18029        public static final int DUMP_PREFERRED_XML = 1 << 13;
18030        public static final int DUMP_KEYSETS = 1 << 14;
18031        public static final int DUMP_VERSION = 1 << 15;
18032        public static final int DUMP_INSTALLS = 1 << 16;
18033        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18034        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18035        public static final int DUMP_FROZEN = 1 << 19;
18036        public static final int DUMP_DEXOPT = 1 << 20;
18037        public static final int DUMP_COMPILER_STATS = 1 << 21;
18038
18039        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18040
18041        private int mTypes;
18042
18043        private int mOptions;
18044
18045        private boolean mTitlePrinted;
18046
18047        private SharedUserSetting mSharedUser;
18048
18049        public boolean isDumping(int type) {
18050            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18051                return true;
18052            }
18053
18054            return (mTypes & type) != 0;
18055        }
18056
18057        public void setDump(int type) {
18058            mTypes |= type;
18059        }
18060
18061        public boolean isOptionEnabled(int option) {
18062            return (mOptions & option) != 0;
18063        }
18064
18065        public void setOptionEnabled(int option) {
18066            mOptions |= option;
18067        }
18068
18069        public boolean onTitlePrinted() {
18070            final boolean printed = mTitlePrinted;
18071            mTitlePrinted = true;
18072            return printed;
18073        }
18074
18075        public boolean getTitlePrinted() {
18076            return mTitlePrinted;
18077        }
18078
18079        public void setTitlePrinted(boolean enabled) {
18080            mTitlePrinted = enabled;
18081        }
18082
18083        public SharedUserSetting getSharedUser() {
18084            return mSharedUser;
18085        }
18086
18087        public void setSharedUser(SharedUserSetting user) {
18088            mSharedUser = user;
18089        }
18090    }
18091
18092    @Override
18093    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18094            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18095        (new PackageManagerShellCommand(this)).exec(
18096                this, in, out, err, args, resultReceiver);
18097    }
18098
18099    @Override
18100    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18101        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18102                != PackageManager.PERMISSION_GRANTED) {
18103            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18104                    + Binder.getCallingPid()
18105                    + ", uid=" + Binder.getCallingUid()
18106                    + " without permission "
18107                    + android.Manifest.permission.DUMP);
18108            return;
18109        }
18110
18111        DumpState dumpState = new DumpState();
18112        boolean fullPreferred = false;
18113        boolean checkin = false;
18114
18115        String packageName = null;
18116        ArraySet<String> permissionNames = null;
18117
18118        int opti = 0;
18119        while (opti < args.length) {
18120            String opt = args[opti];
18121            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18122                break;
18123            }
18124            opti++;
18125
18126            if ("-a".equals(opt)) {
18127                // Right now we only know how to print all.
18128            } else if ("-h".equals(opt)) {
18129                pw.println("Package manager dump options:");
18130                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18131                pw.println("    --checkin: dump for a checkin");
18132                pw.println("    -f: print details of intent filters");
18133                pw.println("    -h: print this help");
18134                pw.println("  cmd may be one of:");
18135                pw.println("    l[ibraries]: list known shared libraries");
18136                pw.println("    f[eatures]: list device features");
18137                pw.println("    k[eysets]: print known keysets");
18138                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18139                pw.println("    perm[issions]: dump permissions");
18140                pw.println("    permission [name ...]: dump declaration and use of given permission");
18141                pw.println("    pref[erred]: print preferred package settings");
18142                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18143                pw.println("    prov[iders]: dump content providers");
18144                pw.println("    p[ackages]: dump installed packages");
18145                pw.println("    s[hared-users]: dump shared user IDs");
18146                pw.println("    m[essages]: print collected runtime messages");
18147                pw.println("    v[erifiers]: print package verifier info");
18148                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18149                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18150                pw.println("    version: print database version info");
18151                pw.println("    write: write current settings now");
18152                pw.println("    installs: details about install sessions");
18153                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18154                pw.println("    dexopt: dump dexopt state");
18155                pw.println("    compiler-stats: dump compiler statistics");
18156                pw.println("    <package.name>: info about given package");
18157                return;
18158            } else if ("--checkin".equals(opt)) {
18159                checkin = true;
18160            } else if ("-f".equals(opt)) {
18161                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18162            } else {
18163                pw.println("Unknown argument: " + opt + "; use -h for help");
18164            }
18165        }
18166
18167        // Is the caller requesting to dump a particular piece of data?
18168        if (opti < args.length) {
18169            String cmd = args[opti];
18170            opti++;
18171            // Is this a package name?
18172            if ("android".equals(cmd) || cmd.contains(".")) {
18173                packageName = cmd;
18174                // When dumping a single package, we always dump all of its
18175                // filter information since the amount of data will be reasonable.
18176                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18177            } else if ("check-permission".equals(cmd)) {
18178                if (opti >= args.length) {
18179                    pw.println("Error: check-permission missing permission argument");
18180                    return;
18181                }
18182                String perm = args[opti];
18183                opti++;
18184                if (opti >= args.length) {
18185                    pw.println("Error: check-permission missing package argument");
18186                    return;
18187                }
18188                String pkg = args[opti];
18189                opti++;
18190                int user = UserHandle.getUserId(Binder.getCallingUid());
18191                if (opti < args.length) {
18192                    try {
18193                        user = Integer.parseInt(args[opti]);
18194                    } catch (NumberFormatException e) {
18195                        pw.println("Error: check-permission user argument is not a number: "
18196                                + args[opti]);
18197                        return;
18198                    }
18199                }
18200                pw.println(checkPermission(perm, pkg, user));
18201                return;
18202            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18203                dumpState.setDump(DumpState.DUMP_LIBS);
18204            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18205                dumpState.setDump(DumpState.DUMP_FEATURES);
18206            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18207                if (opti >= args.length) {
18208                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18209                            | DumpState.DUMP_SERVICE_RESOLVERS
18210                            | DumpState.DUMP_RECEIVER_RESOLVERS
18211                            | DumpState.DUMP_CONTENT_RESOLVERS);
18212                } else {
18213                    while (opti < args.length) {
18214                        String name = args[opti];
18215                        if ("a".equals(name) || "activity".equals(name)) {
18216                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18217                        } else if ("s".equals(name) || "service".equals(name)) {
18218                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18219                        } else if ("r".equals(name) || "receiver".equals(name)) {
18220                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18221                        } else if ("c".equals(name) || "content".equals(name)) {
18222                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18223                        } else {
18224                            pw.println("Error: unknown resolver table type: " + name);
18225                            return;
18226                        }
18227                        opti++;
18228                    }
18229                }
18230            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18231                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18232            } else if ("permission".equals(cmd)) {
18233                if (opti >= args.length) {
18234                    pw.println("Error: permission requires permission name");
18235                    return;
18236                }
18237                permissionNames = new ArraySet<>();
18238                while (opti < args.length) {
18239                    permissionNames.add(args[opti]);
18240                    opti++;
18241                }
18242                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18243                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18244            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18245                dumpState.setDump(DumpState.DUMP_PREFERRED);
18246            } else if ("preferred-xml".equals(cmd)) {
18247                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18248                if (opti < args.length && "--full".equals(args[opti])) {
18249                    fullPreferred = true;
18250                    opti++;
18251                }
18252            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18253                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18254            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18255                dumpState.setDump(DumpState.DUMP_PACKAGES);
18256            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18257                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18258            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18259                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18260            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18261                dumpState.setDump(DumpState.DUMP_MESSAGES);
18262            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18263                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18264            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18265                    || "intent-filter-verifiers".equals(cmd)) {
18266                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18267            } else if ("version".equals(cmd)) {
18268                dumpState.setDump(DumpState.DUMP_VERSION);
18269            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18270                dumpState.setDump(DumpState.DUMP_KEYSETS);
18271            } else if ("installs".equals(cmd)) {
18272                dumpState.setDump(DumpState.DUMP_INSTALLS);
18273            } else if ("frozen".equals(cmd)) {
18274                dumpState.setDump(DumpState.DUMP_FROZEN);
18275            } else if ("dexopt".equals(cmd)) {
18276                dumpState.setDump(DumpState.DUMP_DEXOPT);
18277            } else if ("compiler-stats".equals(cmd)) {
18278                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18279            } else if ("write".equals(cmd)) {
18280                synchronized (mPackages) {
18281                    mSettings.writeLPr();
18282                    pw.println("Settings written.");
18283                    return;
18284                }
18285            }
18286        }
18287
18288        if (checkin) {
18289            pw.println("vers,1");
18290        }
18291
18292        // reader
18293        synchronized (mPackages) {
18294            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18295                if (!checkin) {
18296                    if (dumpState.onTitlePrinted())
18297                        pw.println();
18298                    pw.println("Database versions:");
18299                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18300                }
18301            }
18302
18303            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18304                if (!checkin) {
18305                    if (dumpState.onTitlePrinted())
18306                        pw.println();
18307                    pw.println("Verifiers:");
18308                    pw.print("  Required: ");
18309                    pw.print(mRequiredVerifierPackage);
18310                    pw.print(" (uid=");
18311                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18312                            UserHandle.USER_SYSTEM));
18313                    pw.println(")");
18314                } else if (mRequiredVerifierPackage != null) {
18315                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18316                    pw.print(",");
18317                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18318                            UserHandle.USER_SYSTEM));
18319                }
18320            }
18321
18322            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18323                    packageName == null) {
18324                if (mIntentFilterVerifierComponent != null) {
18325                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18326                    if (!checkin) {
18327                        if (dumpState.onTitlePrinted())
18328                            pw.println();
18329                        pw.println("Intent Filter Verifier:");
18330                        pw.print("  Using: ");
18331                        pw.print(verifierPackageName);
18332                        pw.print(" (uid=");
18333                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18334                                UserHandle.USER_SYSTEM));
18335                        pw.println(")");
18336                    } else if (verifierPackageName != null) {
18337                        pw.print("ifv,"); pw.print(verifierPackageName);
18338                        pw.print(",");
18339                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18340                                UserHandle.USER_SYSTEM));
18341                    }
18342                } else {
18343                    pw.println();
18344                    pw.println("No Intent Filter Verifier available!");
18345                }
18346            }
18347
18348            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18349                boolean printedHeader = false;
18350                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18351                while (it.hasNext()) {
18352                    String name = it.next();
18353                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18354                    if (!checkin) {
18355                        if (!printedHeader) {
18356                            if (dumpState.onTitlePrinted())
18357                                pw.println();
18358                            pw.println("Libraries:");
18359                            printedHeader = true;
18360                        }
18361                        pw.print("  ");
18362                    } else {
18363                        pw.print("lib,");
18364                    }
18365                    pw.print(name);
18366                    if (!checkin) {
18367                        pw.print(" -> ");
18368                    }
18369                    if (ent.path != null) {
18370                        if (!checkin) {
18371                            pw.print("(jar) ");
18372                            pw.print(ent.path);
18373                        } else {
18374                            pw.print(",jar,");
18375                            pw.print(ent.path);
18376                        }
18377                    } else {
18378                        if (!checkin) {
18379                            pw.print("(apk) ");
18380                            pw.print(ent.apk);
18381                        } else {
18382                            pw.print(",apk,");
18383                            pw.print(ent.apk);
18384                        }
18385                    }
18386                    pw.println();
18387                }
18388            }
18389
18390            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18391                if (dumpState.onTitlePrinted())
18392                    pw.println();
18393                if (!checkin) {
18394                    pw.println("Features:");
18395                }
18396
18397                for (FeatureInfo feat : mAvailableFeatures.values()) {
18398                    if (checkin) {
18399                        pw.print("feat,");
18400                        pw.print(feat.name);
18401                        pw.print(",");
18402                        pw.println(feat.version);
18403                    } else {
18404                        pw.print("  ");
18405                        pw.print(feat.name);
18406                        if (feat.version > 0) {
18407                            pw.print(" version=");
18408                            pw.print(feat.version);
18409                        }
18410                        pw.println();
18411                    }
18412                }
18413            }
18414
18415            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18416                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18417                        : "Activity Resolver Table:", "  ", packageName,
18418                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18419                    dumpState.setTitlePrinted(true);
18420                }
18421            }
18422            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18423                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18424                        : "Receiver Resolver Table:", "  ", packageName,
18425                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18426                    dumpState.setTitlePrinted(true);
18427                }
18428            }
18429            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18430                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18431                        : "Service Resolver Table:", "  ", packageName,
18432                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18433                    dumpState.setTitlePrinted(true);
18434                }
18435            }
18436            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18437                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18438                        : "Provider Resolver Table:", "  ", packageName,
18439                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18440                    dumpState.setTitlePrinted(true);
18441                }
18442            }
18443
18444            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18445                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18446                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18447                    int user = mSettings.mPreferredActivities.keyAt(i);
18448                    if (pir.dump(pw,
18449                            dumpState.getTitlePrinted()
18450                                ? "\nPreferred Activities User " + user + ":"
18451                                : "Preferred Activities User " + user + ":", "  ",
18452                            packageName, true, false)) {
18453                        dumpState.setTitlePrinted(true);
18454                    }
18455                }
18456            }
18457
18458            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18459                pw.flush();
18460                FileOutputStream fout = new FileOutputStream(fd);
18461                BufferedOutputStream str = new BufferedOutputStream(fout);
18462                XmlSerializer serializer = new FastXmlSerializer();
18463                try {
18464                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18465                    serializer.startDocument(null, true);
18466                    serializer.setFeature(
18467                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18468                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18469                    serializer.endDocument();
18470                    serializer.flush();
18471                } catch (IllegalArgumentException e) {
18472                    pw.println("Failed writing: " + e);
18473                } catch (IllegalStateException e) {
18474                    pw.println("Failed writing: " + e);
18475                } catch (IOException e) {
18476                    pw.println("Failed writing: " + e);
18477                }
18478            }
18479
18480            if (!checkin
18481                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18482                    && packageName == null) {
18483                pw.println();
18484                int count = mSettings.mPackages.size();
18485                if (count == 0) {
18486                    pw.println("No applications!");
18487                    pw.println();
18488                } else {
18489                    final String prefix = "  ";
18490                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18491                    if (allPackageSettings.size() == 0) {
18492                        pw.println("No domain preferred apps!");
18493                        pw.println();
18494                    } else {
18495                        pw.println("App verification status:");
18496                        pw.println();
18497                        count = 0;
18498                        for (PackageSetting ps : allPackageSettings) {
18499                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18500                            if (ivi == null || ivi.getPackageName() == null) continue;
18501                            pw.println(prefix + "Package: " + ivi.getPackageName());
18502                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18503                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18504                            pw.println();
18505                            count++;
18506                        }
18507                        if (count == 0) {
18508                            pw.println(prefix + "No app verification established.");
18509                            pw.println();
18510                        }
18511                        for (int userId : sUserManager.getUserIds()) {
18512                            pw.println("App linkages for user " + userId + ":");
18513                            pw.println();
18514                            count = 0;
18515                            for (PackageSetting ps : allPackageSettings) {
18516                                final long status = ps.getDomainVerificationStatusForUser(userId);
18517                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18518                                    continue;
18519                                }
18520                                pw.println(prefix + "Package: " + ps.name);
18521                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18522                                String statusStr = IntentFilterVerificationInfo.
18523                                        getStatusStringFromValue(status);
18524                                pw.println(prefix + "Status:  " + statusStr);
18525                                pw.println();
18526                                count++;
18527                            }
18528                            if (count == 0) {
18529                                pw.println(prefix + "No configured app linkages.");
18530                                pw.println();
18531                            }
18532                        }
18533                    }
18534                }
18535            }
18536
18537            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18538                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18539                if (packageName == null && permissionNames == null) {
18540                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18541                        if (iperm == 0) {
18542                            if (dumpState.onTitlePrinted())
18543                                pw.println();
18544                            pw.println("AppOp Permissions:");
18545                        }
18546                        pw.print("  AppOp Permission ");
18547                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18548                        pw.println(":");
18549                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18550                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18551                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18552                        }
18553                    }
18554                }
18555            }
18556
18557            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18558                boolean printedSomething = false;
18559                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18560                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18561                        continue;
18562                    }
18563                    if (!printedSomething) {
18564                        if (dumpState.onTitlePrinted())
18565                            pw.println();
18566                        pw.println("Registered ContentProviders:");
18567                        printedSomething = true;
18568                    }
18569                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18570                    pw.print("    "); pw.println(p.toString());
18571                }
18572                printedSomething = false;
18573                for (Map.Entry<String, PackageParser.Provider> entry :
18574                        mProvidersByAuthority.entrySet()) {
18575                    PackageParser.Provider p = entry.getValue();
18576                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18577                        continue;
18578                    }
18579                    if (!printedSomething) {
18580                        if (dumpState.onTitlePrinted())
18581                            pw.println();
18582                        pw.println("ContentProvider Authorities:");
18583                        printedSomething = true;
18584                    }
18585                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18586                    pw.print("    "); pw.println(p.toString());
18587                    if (p.info != null && p.info.applicationInfo != null) {
18588                        final String appInfo = p.info.applicationInfo.toString();
18589                        pw.print("      applicationInfo="); pw.println(appInfo);
18590                    }
18591                }
18592            }
18593
18594            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18595                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18596            }
18597
18598            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18599                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18600            }
18601
18602            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18603                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18604            }
18605
18606            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18607                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18608            }
18609
18610            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18611                // XXX should handle packageName != null by dumping only install data that
18612                // the given package is involved with.
18613                if (dumpState.onTitlePrinted()) pw.println();
18614                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18615            }
18616
18617            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18618                // XXX should handle packageName != null by dumping only install data that
18619                // the given package is involved with.
18620                if (dumpState.onTitlePrinted()) pw.println();
18621
18622                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18623                ipw.println();
18624                ipw.println("Frozen packages:");
18625                ipw.increaseIndent();
18626                if (mFrozenPackages.size() == 0) {
18627                    ipw.println("(none)");
18628                } else {
18629                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18630                        ipw.println(mFrozenPackages.valueAt(i));
18631                    }
18632                }
18633                ipw.decreaseIndent();
18634            }
18635
18636            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18637                if (dumpState.onTitlePrinted()) pw.println();
18638                dumpDexoptStateLPr(pw, packageName);
18639            }
18640
18641            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
18642                if (dumpState.onTitlePrinted()) pw.println();
18643                dumpCompilerStatsLPr(pw, packageName);
18644            }
18645
18646            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18647                if (dumpState.onTitlePrinted()) pw.println();
18648                mSettings.dumpReadMessagesLPr(pw, dumpState);
18649
18650                pw.println();
18651                pw.println("Package warning messages:");
18652                BufferedReader in = null;
18653                String line = null;
18654                try {
18655                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18656                    while ((line = in.readLine()) != null) {
18657                        if (line.contains("ignored: updated version")) continue;
18658                        pw.println(line);
18659                    }
18660                } catch (IOException ignored) {
18661                } finally {
18662                    IoUtils.closeQuietly(in);
18663                }
18664            }
18665
18666            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18667                BufferedReader in = null;
18668                String line = null;
18669                try {
18670                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18671                    while ((line = in.readLine()) != null) {
18672                        if (line.contains("ignored: updated version")) continue;
18673                        pw.print("msg,");
18674                        pw.println(line);
18675                    }
18676                } catch (IOException ignored) {
18677                } finally {
18678                    IoUtils.closeQuietly(in);
18679                }
18680            }
18681        }
18682    }
18683
18684    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18685        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18686        ipw.println();
18687        ipw.println("Dexopt state:");
18688        ipw.increaseIndent();
18689        Collection<PackageParser.Package> packages = null;
18690        if (packageName != null) {
18691            PackageParser.Package targetPackage = mPackages.get(packageName);
18692            if (targetPackage != null) {
18693                packages = Collections.singletonList(targetPackage);
18694            } else {
18695                ipw.println("Unable to find package: " + packageName);
18696                return;
18697            }
18698        } else {
18699            packages = mPackages.values();
18700        }
18701
18702        for (PackageParser.Package pkg : packages) {
18703            ipw.println("[" + pkg.packageName + "]");
18704            ipw.increaseIndent();
18705            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18706            ipw.decreaseIndent();
18707        }
18708    }
18709
18710    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
18711        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18712        ipw.println();
18713        ipw.println("Compiler stats:");
18714        ipw.increaseIndent();
18715        Collection<PackageParser.Package> packages = null;
18716        if (packageName != null) {
18717            PackageParser.Package targetPackage = mPackages.get(packageName);
18718            if (targetPackage != null) {
18719                packages = Collections.singletonList(targetPackage);
18720            } else {
18721                ipw.println("Unable to find package: " + packageName);
18722                return;
18723            }
18724        } else {
18725            packages = mPackages.values();
18726        }
18727
18728        for (PackageParser.Package pkg : packages) {
18729            ipw.println("[" + pkg.packageName + "]");
18730            ipw.increaseIndent();
18731
18732            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
18733            if (stats == null) {
18734                ipw.println("(No recorded stats)");
18735            } else {
18736                stats.dump(ipw);
18737            }
18738            ipw.decreaseIndent();
18739        }
18740    }
18741
18742    private String dumpDomainString(String packageName) {
18743        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18744                .getList();
18745        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18746
18747        ArraySet<String> result = new ArraySet<>();
18748        if (iviList.size() > 0) {
18749            for (IntentFilterVerificationInfo ivi : iviList) {
18750                for (String host : ivi.getDomains()) {
18751                    result.add(host);
18752                }
18753            }
18754        }
18755        if (filters != null && filters.size() > 0) {
18756            for (IntentFilter filter : filters) {
18757                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18758                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18759                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18760                    result.addAll(filter.getHostsList());
18761                }
18762            }
18763        }
18764
18765        StringBuilder sb = new StringBuilder(result.size() * 16);
18766        for (String domain : result) {
18767            if (sb.length() > 0) sb.append(" ");
18768            sb.append(domain);
18769        }
18770        return sb.toString();
18771    }
18772
18773    // ------- apps on sdcard specific code -------
18774    static final boolean DEBUG_SD_INSTALL = false;
18775
18776    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18777
18778    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18779
18780    private boolean mMediaMounted = false;
18781
18782    static String getEncryptKey() {
18783        try {
18784            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18785                    SD_ENCRYPTION_KEYSTORE_NAME);
18786            if (sdEncKey == null) {
18787                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18788                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18789                if (sdEncKey == null) {
18790                    Slog.e(TAG, "Failed to create encryption keys");
18791                    return null;
18792                }
18793            }
18794            return sdEncKey;
18795        } catch (NoSuchAlgorithmException nsae) {
18796            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18797            return null;
18798        } catch (IOException ioe) {
18799            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18800            return null;
18801        }
18802    }
18803
18804    /*
18805     * Update media status on PackageManager.
18806     */
18807    @Override
18808    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18809        int callingUid = Binder.getCallingUid();
18810        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18811            throw new SecurityException("Media status can only be updated by the system");
18812        }
18813        // reader; this apparently protects mMediaMounted, but should probably
18814        // be a different lock in that case.
18815        synchronized (mPackages) {
18816            Log.i(TAG, "Updating external media status from "
18817                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18818                    + (mediaStatus ? "mounted" : "unmounted"));
18819            if (DEBUG_SD_INSTALL)
18820                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18821                        + ", mMediaMounted=" + mMediaMounted);
18822            if (mediaStatus == mMediaMounted) {
18823                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18824                        : 0, -1);
18825                mHandler.sendMessage(msg);
18826                return;
18827            }
18828            mMediaMounted = mediaStatus;
18829        }
18830        // Queue up an async operation since the package installation may take a
18831        // little while.
18832        mHandler.post(new Runnable() {
18833            public void run() {
18834                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18835            }
18836        });
18837    }
18838
18839    /**
18840     * Called by MountService when the initial ASECs to scan are available.
18841     * Should block until all the ASEC containers are finished being scanned.
18842     */
18843    public void scanAvailableAsecs() {
18844        updateExternalMediaStatusInner(true, false, false);
18845    }
18846
18847    /*
18848     * Collect information of applications on external media, map them against
18849     * existing containers and update information based on current mount status.
18850     * Please note that we always have to report status if reportStatus has been
18851     * set to true especially when unloading packages.
18852     */
18853    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18854            boolean externalStorage) {
18855        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18856        int[] uidArr = EmptyArray.INT;
18857
18858        final String[] list = PackageHelper.getSecureContainerList();
18859        if (ArrayUtils.isEmpty(list)) {
18860            Log.i(TAG, "No secure containers found");
18861        } else {
18862            // Process list of secure containers and categorize them
18863            // as active or stale based on their package internal state.
18864
18865            // reader
18866            synchronized (mPackages) {
18867                for (String cid : list) {
18868                    // Leave stages untouched for now; installer service owns them
18869                    if (PackageInstallerService.isStageName(cid)) continue;
18870
18871                    if (DEBUG_SD_INSTALL)
18872                        Log.i(TAG, "Processing container " + cid);
18873                    String pkgName = getAsecPackageName(cid);
18874                    if (pkgName == null) {
18875                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18876                        continue;
18877                    }
18878                    if (DEBUG_SD_INSTALL)
18879                        Log.i(TAG, "Looking for pkg : " + pkgName);
18880
18881                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18882                    if (ps == null) {
18883                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18884                        continue;
18885                    }
18886
18887                    /*
18888                     * Skip packages that are not external if we're unmounting
18889                     * external storage.
18890                     */
18891                    if (externalStorage && !isMounted && !isExternal(ps)) {
18892                        continue;
18893                    }
18894
18895                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18896                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18897                    // The package status is changed only if the code path
18898                    // matches between settings and the container id.
18899                    if (ps.codePathString != null
18900                            && ps.codePathString.startsWith(args.getCodePath())) {
18901                        if (DEBUG_SD_INSTALL) {
18902                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18903                                    + " at code path: " + ps.codePathString);
18904                        }
18905
18906                        // We do have a valid package installed on sdcard
18907                        processCids.put(args, ps.codePathString);
18908                        final int uid = ps.appId;
18909                        if (uid != -1) {
18910                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18911                        }
18912                    } else {
18913                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18914                                + ps.codePathString);
18915                    }
18916                }
18917            }
18918
18919            Arrays.sort(uidArr);
18920        }
18921
18922        // Process packages with valid entries.
18923        if (isMounted) {
18924            if (DEBUG_SD_INSTALL)
18925                Log.i(TAG, "Loading packages");
18926            loadMediaPackages(processCids, uidArr, externalStorage);
18927            startCleaningPackages();
18928            mInstallerService.onSecureContainersAvailable();
18929        } else {
18930            if (DEBUG_SD_INSTALL)
18931                Log.i(TAG, "Unloading packages");
18932            unloadMediaPackages(processCids, uidArr, reportStatus);
18933        }
18934    }
18935
18936    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18937            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18938        final int size = infos.size();
18939        final String[] packageNames = new String[size];
18940        final int[] packageUids = new int[size];
18941        for (int i = 0; i < size; i++) {
18942            final ApplicationInfo info = infos.get(i);
18943            packageNames[i] = info.packageName;
18944            packageUids[i] = info.uid;
18945        }
18946        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18947                finishedReceiver);
18948    }
18949
18950    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18951            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18952        sendResourcesChangedBroadcast(mediaStatus, replacing,
18953                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18954    }
18955
18956    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18957            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18958        int size = pkgList.length;
18959        if (size > 0) {
18960            // Send broadcasts here
18961            Bundle extras = new Bundle();
18962            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18963            if (uidArr != null) {
18964                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18965            }
18966            if (replacing) {
18967                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18968            }
18969            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18970                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18971            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18972        }
18973    }
18974
18975   /*
18976     * Look at potentially valid container ids from processCids If package
18977     * information doesn't match the one on record or package scanning fails,
18978     * the cid is added to list of removeCids. We currently don't delete stale
18979     * containers.
18980     */
18981    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18982            boolean externalStorage) {
18983        ArrayList<String> pkgList = new ArrayList<String>();
18984        Set<AsecInstallArgs> keys = processCids.keySet();
18985
18986        for (AsecInstallArgs args : keys) {
18987            String codePath = processCids.get(args);
18988            if (DEBUG_SD_INSTALL)
18989                Log.i(TAG, "Loading container : " + args.cid);
18990            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18991            try {
18992                // Make sure there are no container errors first.
18993                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18994                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18995                            + " when installing from sdcard");
18996                    continue;
18997                }
18998                // Check code path here.
18999                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19000                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19001                            + " does not match one in settings " + codePath);
19002                    continue;
19003                }
19004                // Parse package
19005                int parseFlags = mDefParseFlags;
19006                if (args.isExternalAsec()) {
19007                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19008                }
19009                if (args.isFwdLocked()) {
19010                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19011                }
19012
19013                synchronized (mInstallLock) {
19014                    PackageParser.Package pkg = null;
19015                    try {
19016                        // Sadly we don't know the package name yet to freeze it
19017                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19018                                SCAN_IGNORE_FROZEN, 0, null);
19019                    } catch (PackageManagerException e) {
19020                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19021                    }
19022                    // Scan the package
19023                    if (pkg != null) {
19024                        /*
19025                         * TODO why is the lock being held? doPostInstall is
19026                         * called in other places without the lock. This needs
19027                         * to be straightened out.
19028                         */
19029                        // writer
19030                        synchronized (mPackages) {
19031                            retCode = PackageManager.INSTALL_SUCCEEDED;
19032                            pkgList.add(pkg.packageName);
19033                            // Post process args
19034                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19035                                    pkg.applicationInfo.uid);
19036                        }
19037                    } else {
19038                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19039                    }
19040                }
19041
19042            } finally {
19043                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19044                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19045                }
19046            }
19047        }
19048        // writer
19049        synchronized (mPackages) {
19050            // If the platform SDK has changed since the last time we booted,
19051            // we need to re-grant app permission to catch any new ones that
19052            // appear. This is really a hack, and means that apps can in some
19053            // cases get permissions that the user didn't initially explicitly
19054            // allow... it would be nice to have some better way to handle
19055            // this situation.
19056            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19057                    : mSettings.getInternalVersion();
19058            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19059                    : StorageManager.UUID_PRIVATE_INTERNAL;
19060
19061            int updateFlags = UPDATE_PERMISSIONS_ALL;
19062            if (ver.sdkVersion != mSdkVersion) {
19063                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19064                        + mSdkVersion + "; regranting permissions for external");
19065                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19066            }
19067            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19068
19069            // Yay, everything is now upgraded
19070            ver.forceCurrent();
19071
19072            // can downgrade to reader
19073            // Persist settings
19074            mSettings.writeLPr();
19075        }
19076        // Send a broadcast to let everyone know we are done processing
19077        if (pkgList.size() > 0) {
19078            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19079        }
19080    }
19081
19082   /*
19083     * Utility method to unload a list of specified containers
19084     */
19085    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19086        // Just unmount all valid containers.
19087        for (AsecInstallArgs arg : cidArgs) {
19088            synchronized (mInstallLock) {
19089                arg.doPostDeleteLI(false);
19090           }
19091       }
19092   }
19093
19094    /*
19095     * Unload packages mounted on external media. This involves deleting package
19096     * data from internal structures, sending broadcasts about disabled packages,
19097     * gc'ing to free up references, unmounting all secure containers
19098     * corresponding to packages on external media, and posting a
19099     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19100     * that we always have to post this message if status has been requested no
19101     * matter what.
19102     */
19103    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19104            final boolean reportStatus) {
19105        if (DEBUG_SD_INSTALL)
19106            Log.i(TAG, "unloading media packages");
19107        ArrayList<String> pkgList = new ArrayList<String>();
19108        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19109        final Set<AsecInstallArgs> keys = processCids.keySet();
19110        for (AsecInstallArgs args : keys) {
19111            String pkgName = args.getPackageName();
19112            if (DEBUG_SD_INSTALL)
19113                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19114            // Delete package internally
19115            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19116            synchronized (mInstallLock) {
19117                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19118                final boolean res;
19119                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19120                        "unloadMediaPackages")) {
19121                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19122                            null);
19123                }
19124                if (res) {
19125                    pkgList.add(pkgName);
19126                } else {
19127                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19128                    failedList.add(args);
19129                }
19130            }
19131        }
19132
19133        // reader
19134        synchronized (mPackages) {
19135            // We didn't update the settings after removing each package;
19136            // write them now for all packages.
19137            mSettings.writeLPr();
19138        }
19139
19140        // We have to absolutely send UPDATED_MEDIA_STATUS only
19141        // after confirming that all the receivers processed the ordered
19142        // broadcast when packages get disabled, force a gc to clean things up.
19143        // and unload all the containers.
19144        if (pkgList.size() > 0) {
19145            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19146                    new IIntentReceiver.Stub() {
19147                public void performReceive(Intent intent, int resultCode, String data,
19148                        Bundle extras, boolean ordered, boolean sticky,
19149                        int sendingUser) throws RemoteException {
19150                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19151                            reportStatus ? 1 : 0, 1, keys);
19152                    mHandler.sendMessage(msg);
19153                }
19154            });
19155        } else {
19156            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19157                    keys);
19158            mHandler.sendMessage(msg);
19159        }
19160    }
19161
19162    private void loadPrivatePackages(final VolumeInfo vol) {
19163        mHandler.post(new Runnable() {
19164            @Override
19165            public void run() {
19166                loadPrivatePackagesInner(vol);
19167            }
19168        });
19169    }
19170
19171    private void loadPrivatePackagesInner(VolumeInfo vol) {
19172        final String volumeUuid = vol.fsUuid;
19173        if (TextUtils.isEmpty(volumeUuid)) {
19174            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19175            return;
19176        }
19177
19178        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19179        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19180        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19181
19182        final VersionInfo ver;
19183        final List<PackageSetting> packages;
19184        synchronized (mPackages) {
19185            ver = mSettings.findOrCreateVersion(volumeUuid);
19186            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19187        }
19188
19189        for (PackageSetting ps : packages) {
19190            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19191            synchronized (mInstallLock) {
19192                final PackageParser.Package pkg;
19193                try {
19194                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19195                    loaded.add(pkg.applicationInfo);
19196
19197                } catch (PackageManagerException e) {
19198                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19199                }
19200
19201                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19202                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19203                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19204                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19205                }
19206            }
19207        }
19208
19209        // Reconcile app data for all started/unlocked users
19210        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19211        final UserManager um = mContext.getSystemService(UserManager.class);
19212        UserManagerInternal umInternal = getUserManagerInternal();
19213        for (UserInfo user : um.getUsers()) {
19214            final int flags;
19215            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19216                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19217            } else if (umInternal.isUserRunning(user.id)) {
19218                flags = StorageManager.FLAG_STORAGE_DE;
19219            } else {
19220                continue;
19221            }
19222
19223            try {
19224                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19225                synchronized (mInstallLock) {
19226                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19227                }
19228            } catch (IllegalStateException e) {
19229                // Device was probably ejected, and we'll process that event momentarily
19230                Slog.w(TAG, "Failed to prepare storage: " + e);
19231            }
19232        }
19233
19234        synchronized (mPackages) {
19235            int updateFlags = UPDATE_PERMISSIONS_ALL;
19236            if (ver.sdkVersion != mSdkVersion) {
19237                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19238                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19239                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19240            }
19241            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19242
19243            // Yay, everything is now upgraded
19244            ver.forceCurrent();
19245
19246            mSettings.writeLPr();
19247        }
19248
19249        for (PackageFreezer freezer : freezers) {
19250            freezer.close();
19251        }
19252
19253        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19254        sendResourcesChangedBroadcast(true, false, loaded, null);
19255    }
19256
19257    private void unloadPrivatePackages(final VolumeInfo vol) {
19258        mHandler.post(new Runnable() {
19259            @Override
19260            public void run() {
19261                unloadPrivatePackagesInner(vol);
19262            }
19263        });
19264    }
19265
19266    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19267        final String volumeUuid = vol.fsUuid;
19268        if (TextUtils.isEmpty(volumeUuid)) {
19269            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19270            return;
19271        }
19272
19273        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19274        synchronized (mInstallLock) {
19275        synchronized (mPackages) {
19276            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19277            for (PackageSetting ps : packages) {
19278                if (ps.pkg == null) continue;
19279
19280                final ApplicationInfo info = ps.pkg.applicationInfo;
19281                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19282                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19283
19284                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19285                        "unloadPrivatePackagesInner")) {
19286                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19287                            false, null)) {
19288                        unloaded.add(info);
19289                    } else {
19290                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19291                    }
19292                }
19293
19294                // Try very hard to release any references to this package
19295                // so we don't risk the system server being killed due to
19296                // open FDs
19297                AttributeCache.instance().removePackage(ps.name);
19298            }
19299
19300            mSettings.writeLPr();
19301        }
19302        }
19303
19304        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19305        sendResourcesChangedBroadcast(false, false, unloaded, null);
19306
19307        // Try very hard to release any references to this path so we don't risk
19308        // the system server being killed due to open FDs
19309        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19310
19311        for (int i = 0; i < 3; i++) {
19312            System.gc();
19313            System.runFinalization();
19314        }
19315    }
19316
19317    /**
19318     * Prepare storage areas for given user on all mounted devices.
19319     */
19320    void prepareUserData(int userId, int userSerial, int flags) {
19321        synchronized (mInstallLock) {
19322            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19323            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19324                final String volumeUuid = vol.getFsUuid();
19325                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19326            }
19327        }
19328    }
19329
19330    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19331            boolean allowRecover) {
19332        // Prepare storage and verify that serial numbers are consistent; if
19333        // there's a mismatch we need to destroy to avoid leaking data
19334        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19335        try {
19336            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19337
19338            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19339                UserManagerService.enforceSerialNumber(
19340                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19341                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19342                    UserManagerService.enforceSerialNumber(
19343                            Environment.getDataSystemDeDirectory(userId), userSerial);
19344                }
19345            }
19346            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19347                UserManagerService.enforceSerialNumber(
19348                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19349                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19350                    UserManagerService.enforceSerialNumber(
19351                            Environment.getDataSystemCeDirectory(userId), userSerial);
19352                }
19353            }
19354
19355            synchronized (mInstallLock) {
19356                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19357            }
19358        } catch (Exception e) {
19359            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19360                    + " because we failed to prepare: " + e);
19361            destroyUserDataLI(volumeUuid, userId,
19362                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19363
19364            if (allowRecover) {
19365                // Try one last time; if we fail again we're really in trouble
19366                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19367            }
19368        }
19369    }
19370
19371    /**
19372     * Destroy storage areas for given user on all mounted devices.
19373     */
19374    void destroyUserData(int userId, int flags) {
19375        synchronized (mInstallLock) {
19376            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19377            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19378                final String volumeUuid = vol.getFsUuid();
19379                destroyUserDataLI(volumeUuid, userId, flags);
19380            }
19381        }
19382    }
19383
19384    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19385        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19386        try {
19387            // Clean up app data, profile data, and media data
19388            mInstaller.destroyUserData(volumeUuid, userId, flags);
19389
19390            // Clean up system data
19391            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19392                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19393                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19394                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19395                }
19396                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19397                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19398                }
19399            }
19400
19401            // Data with special labels is now gone, so finish the job
19402            storage.destroyUserStorage(volumeUuid, userId, flags);
19403
19404        } catch (Exception e) {
19405            logCriticalInfo(Log.WARN,
19406                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19407        }
19408    }
19409
19410    /**
19411     * Examine all users present on given mounted volume, and destroy data
19412     * belonging to users that are no longer valid, or whose user ID has been
19413     * recycled.
19414     */
19415    private void reconcileUsers(String volumeUuid) {
19416        final List<File> files = new ArrayList<>();
19417        Collections.addAll(files, FileUtils
19418                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19419        Collections.addAll(files, FileUtils
19420                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19421        Collections.addAll(files, FileUtils
19422                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19423        Collections.addAll(files, FileUtils
19424                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19425        for (File file : files) {
19426            if (!file.isDirectory()) continue;
19427
19428            final int userId;
19429            final UserInfo info;
19430            try {
19431                userId = Integer.parseInt(file.getName());
19432                info = sUserManager.getUserInfo(userId);
19433            } catch (NumberFormatException e) {
19434                Slog.w(TAG, "Invalid user directory " + file);
19435                continue;
19436            }
19437
19438            boolean destroyUser = false;
19439            if (info == null) {
19440                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19441                        + " because no matching user was found");
19442                destroyUser = true;
19443            } else if (!mOnlyCore) {
19444                try {
19445                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19446                } catch (IOException e) {
19447                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19448                            + " because we failed to enforce serial number: " + e);
19449                    destroyUser = true;
19450                }
19451            }
19452
19453            if (destroyUser) {
19454                synchronized (mInstallLock) {
19455                    destroyUserDataLI(volumeUuid, userId,
19456                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19457                }
19458            }
19459        }
19460    }
19461
19462    private void assertPackageKnown(String volumeUuid, String packageName)
19463            throws PackageManagerException {
19464        synchronized (mPackages) {
19465            final PackageSetting ps = mSettings.mPackages.get(packageName);
19466            if (ps == null) {
19467                throw new PackageManagerException("Package " + packageName + " is unknown");
19468            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19469                throw new PackageManagerException(
19470                        "Package " + packageName + " found on unknown volume " + volumeUuid
19471                                + "; expected volume " + ps.volumeUuid);
19472            }
19473        }
19474    }
19475
19476    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19477            throws PackageManagerException {
19478        synchronized (mPackages) {
19479            final PackageSetting ps = mSettings.mPackages.get(packageName);
19480            if (ps == null) {
19481                throw new PackageManagerException("Package " + packageName + " is unknown");
19482            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19483                throw new PackageManagerException(
19484                        "Package " + packageName + " found on unknown volume " + volumeUuid
19485                                + "; expected volume " + ps.volumeUuid);
19486            } else if (!ps.getInstalled(userId)) {
19487                throw new PackageManagerException(
19488                        "Package " + packageName + " not installed for user " + userId);
19489            }
19490        }
19491    }
19492
19493    /**
19494     * Examine all apps present on given mounted volume, and destroy apps that
19495     * aren't expected, either due to uninstallation or reinstallation on
19496     * another volume.
19497     */
19498    private void reconcileApps(String volumeUuid) {
19499        final File[] files = FileUtils
19500                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19501        for (File file : files) {
19502            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19503                    && !PackageInstallerService.isStageName(file.getName());
19504            if (!isPackage) {
19505                // Ignore entries which are not packages
19506                continue;
19507            }
19508
19509            try {
19510                final PackageLite pkg = PackageParser.parsePackageLite(file,
19511                        PackageParser.PARSE_MUST_BE_APK);
19512                assertPackageKnown(volumeUuid, pkg.packageName);
19513
19514            } catch (PackageParserException | PackageManagerException e) {
19515                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19516                synchronized (mInstallLock) {
19517                    removeCodePathLI(file);
19518                }
19519            }
19520        }
19521    }
19522
19523    /**
19524     * Reconcile all app data for the given user.
19525     * <p>
19526     * Verifies that directories exist and that ownership and labeling is
19527     * correct for all installed apps on all mounted volumes.
19528     */
19529    void reconcileAppsData(int userId, int flags) {
19530        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19531        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19532            final String volumeUuid = vol.getFsUuid();
19533            synchronized (mInstallLock) {
19534                reconcileAppsDataLI(volumeUuid, userId, flags);
19535            }
19536        }
19537    }
19538
19539    /**
19540     * Reconcile all app data on given mounted volume.
19541     * <p>
19542     * Destroys app data that isn't expected, either due to uninstallation or
19543     * reinstallation on another volume.
19544     * <p>
19545     * Verifies that directories exist and that ownership and labeling is
19546     * correct for all installed apps.
19547     */
19548    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19549        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19550                + Integer.toHexString(flags));
19551
19552        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19553        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19554
19555        boolean restoreconNeeded = false;
19556
19557        // First look for stale data that doesn't belong, and check if things
19558        // have changed since we did our last restorecon
19559        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19560            if (StorageManager.isFileEncryptedNativeOrEmulated()
19561                    && !StorageManager.isUserKeyUnlocked(userId)) {
19562                throw new RuntimeException(
19563                        "Yikes, someone asked us to reconcile CE storage while " + userId
19564                                + " was still locked; this would have caused massive data loss!");
19565            }
19566
19567            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19568
19569            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19570            for (File file : files) {
19571                final String packageName = file.getName();
19572                try {
19573                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19574                } catch (PackageManagerException e) {
19575                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19576                    try {
19577                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19578                                StorageManager.FLAG_STORAGE_CE, 0);
19579                    } catch (InstallerException e2) {
19580                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19581                    }
19582                }
19583            }
19584        }
19585        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19586            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19587
19588            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19589            for (File file : files) {
19590                final String packageName = file.getName();
19591                try {
19592                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19593                } catch (PackageManagerException e) {
19594                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19595                    try {
19596                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19597                                StorageManager.FLAG_STORAGE_DE, 0);
19598                    } catch (InstallerException e2) {
19599                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19600                    }
19601                }
19602            }
19603        }
19604
19605        // Ensure that data directories are ready to roll for all packages
19606        // installed for this volume and user
19607        final List<PackageSetting> packages;
19608        synchronized (mPackages) {
19609            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19610        }
19611        int preparedCount = 0;
19612        for (PackageSetting ps : packages) {
19613            final String packageName = ps.name;
19614            if (ps.pkg == null) {
19615                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19616                // TODO: might be due to legacy ASEC apps; we should circle back
19617                // and reconcile again once they're scanned
19618                continue;
19619            }
19620
19621            if (ps.getInstalled(userId)) {
19622                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19623
19624                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19625                    // We may have just shuffled around app data directories, so
19626                    // prepare them one more time
19627                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19628                }
19629
19630                preparedCount++;
19631            }
19632        }
19633
19634        if (restoreconNeeded) {
19635            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19636                SELinuxMMAC.setRestoreconDone(ceDir);
19637            }
19638            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19639                SELinuxMMAC.setRestoreconDone(deDir);
19640            }
19641        }
19642
19643        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19644                + " packages; restoreconNeeded was " + restoreconNeeded);
19645    }
19646
19647    /**
19648     * Prepare app data for the given app just after it was installed or
19649     * upgraded. This method carefully only touches users that it's installed
19650     * for, and it forces a restorecon to handle any seinfo changes.
19651     * <p>
19652     * Verifies that directories exist and that ownership and labeling is
19653     * correct for all installed apps. If there is an ownership mismatch, it
19654     * will try recovering system apps by wiping data; third-party app data is
19655     * left intact.
19656     * <p>
19657     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19658     */
19659    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19660        final PackageSetting ps;
19661        synchronized (mPackages) {
19662            ps = mSettings.mPackages.get(pkg.packageName);
19663            mSettings.writeKernelMappingLPr(ps);
19664        }
19665
19666        final UserManager um = mContext.getSystemService(UserManager.class);
19667        UserManagerInternal umInternal = getUserManagerInternal();
19668        for (UserInfo user : um.getUsers()) {
19669            final int flags;
19670            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19671                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19672            } else if (umInternal.isUserRunning(user.id)) {
19673                flags = StorageManager.FLAG_STORAGE_DE;
19674            } else {
19675                continue;
19676            }
19677
19678            if (ps.getInstalled(user.id)) {
19679                // Whenever an app changes, force a restorecon of its data
19680                // TODO: when user data is locked, mark that we're still dirty
19681                prepareAppDataLIF(pkg, user.id, flags, true);
19682            }
19683        }
19684    }
19685
19686    /**
19687     * Prepare app data for the given app.
19688     * <p>
19689     * Verifies that directories exist and that ownership and labeling is
19690     * correct for all installed apps. If there is an ownership mismatch, this
19691     * will try recovering system apps by wiping data; third-party app data is
19692     * left intact.
19693     */
19694    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19695            boolean restoreconNeeded) {
19696        if (pkg == null) {
19697            Slog.wtf(TAG, "Package was null!", new Throwable());
19698            return;
19699        }
19700        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19701        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19702        for (int i = 0; i < childCount; i++) {
19703            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19704        }
19705    }
19706
19707    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19708            boolean restoreconNeeded) {
19709        if (DEBUG_APP_DATA) {
19710            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19711                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19712        }
19713
19714        final String volumeUuid = pkg.volumeUuid;
19715        final String packageName = pkg.packageName;
19716        final ApplicationInfo app = pkg.applicationInfo;
19717        final int appId = UserHandle.getAppId(app.uid);
19718
19719        Preconditions.checkNotNull(app.seinfo);
19720
19721        try {
19722            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19723                    appId, app.seinfo, app.targetSdkVersion);
19724        } catch (InstallerException e) {
19725            if (app.isSystemApp()) {
19726                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19727                        + ", but trying to recover: " + e);
19728                destroyAppDataLeafLIF(pkg, userId, flags);
19729                try {
19730                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19731                            appId, app.seinfo, app.targetSdkVersion);
19732                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19733                } catch (InstallerException e2) {
19734                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19735                }
19736            } else {
19737                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19738            }
19739        }
19740
19741        if (restoreconNeeded) {
19742            try {
19743                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19744                        app.seinfo);
19745            } catch (InstallerException e) {
19746                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19747            }
19748        }
19749
19750        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19751            try {
19752                // CE storage is unlocked right now, so read out the inode and
19753                // remember for use later when it's locked
19754                // TODO: mark this structure as dirty so we persist it!
19755                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19756                        StorageManager.FLAG_STORAGE_CE);
19757                synchronized (mPackages) {
19758                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19759                    if (ps != null) {
19760                        ps.setCeDataInode(ceDataInode, userId);
19761                    }
19762                }
19763            } catch (InstallerException e) {
19764                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19765            }
19766        }
19767
19768        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19769    }
19770
19771    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19772        if (pkg == null) {
19773            Slog.wtf(TAG, "Package was null!", new Throwable());
19774            return;
19775        }
19776        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19777        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19778        for (int i = 0; i < childCount; i++) {
19779            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19780        }
19781    }
19782
19783    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19784        final String volumeUuid = pkg.volumeUuid;
19785        final String packageName = pkg.packageName;
19786        final ApplicationInfo app = pkg.applicationInfo;
19787
19788        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19789            // Create a native library symlink only if we have native libraries
19790            // and if the native libraries are 32 bit libraries. We do not provide
19791            // this symlink for 64 bit libraries.
19792            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19793                final String nativeLibPath = app.nativeLibraryDir;
19794                try {
19795                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19796                            nativeLibPath, userId);
19797                } catch (InstallerException e) {
19798                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19799                }
19800            }
19801        }
19802    }
19803
19804    /**
19805     * For system apps on non-FBE devices, this method migrates any existing
19806     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19807     * requested by the app.
19808     */
19809    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19810        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19811                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19812            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19813                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19814            try {
19815                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19816                        storageTarget);
19817            } catch (InstallerException e) {
19818                logCriticalInfo(Log.WARN,
19819                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19820            }
19821            return true;
19822        } else {
19823            return false;
19824        }
19825    }
19826
19827    public PackageFreezer freezePackage(String packageName, String killReason) {
19828        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
19829    }
19830
19831    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
19832        return new PackageFreezer(packageName, userId, killReason);
19833    }
19834
19835    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19836            String killReason) {
19837        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
19838    }
19839
19840    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
19841            String killReason) {
19842        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19843            return new PackageFreezer();
19844        } else {
19845            return freezePackage(packageName, userId, killReason);
19846        }
19847    }
19848
19849    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19850            String killReason) {
19851        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
19852    }
19853
19854    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
19855            String killReason) {
19856        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19857            return new PackageFreezer();
19858        } else {
19859            return freezePackage(packageName, userId, killReason);
19860        }
19861    }
19862
19863    /**
19864     * Class that freezes and kills the given package upon creation, and
19865     * unfreezes it upon closing. This is typically used when doing surgery on
19866     * app code/data to prevent the app from running while you're working.
19867     */
19868    private class PackageFreezer implements AutoCloseable {
19869        private final String mPackageName;
19870        private final PackageFreezer[] mChildren;
19871
19872        private final boolean mWeFroze;
19873
19874        private final AtomicBoolean mClosed = new AtomicBoolean();
19875        private final CloseGuard mCloseGuard = CloseGuard.get();
19876
19877        /**
19878         * Create and return a stub freezer that doesn't actually do anything,
19879         * typically used when someone requested
19880         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19881         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19882         */
19883        public PackageFreezer() {
19884            mPackageName = null;
19885            mChildren = null;
19886            mWeFroze = false;
19887            mCloseGuard.open("close");
19888        }
19889
19890        public PackageFreezer(String packageName, int userId, String killReason) {
19891            synchronized (mPackages) {
19892                mPackageName = packageName;
19893                mWeFroze = mFrozenPackages.add(mPackageName);
19894
19895                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19896                if (ps != null) {
19897                    killApplication(ps.name, ps.appId, userId, killReason);
19898                }
19899
19900                final PackageParser.Package p = mPackages.get(packageName);
19901                if (p != null && p.childPackages != null) {
19902                    final int N = p.childPackages.size();
19903                    mChildren = new PackageFreezer[N];
19904                    for (int i = 0; i < N; i++) {
19905                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19906                                userId, killReason);
19907                    }
19908                } else {
19909                    mChildren = null;
19910                }
19911            }
19912            mCloseGuard.open("close");
19913        }
19914
19915        @Override
19916        protected void finalize() throws Throwable {
19917            try {
19918                mCloseGuard.warnIfOpen();
19919                close();
19920            } finally {
19921                super.finalize();
19922            }
19923        }
19924
19925        @Override
19926        public void close() {
19927            mCloseGuard.close();
19928            if (mClosed.compareAndSet(false, true)) {
19929                synchronized (mPackages) {
19930                    if (mWeFroze) {
19931                        mFrozenPackages.remove(mPackageName);
19932                    }
19933
19934                    if (mChildren != null) {
19935                        for (PackageFreezer freezer : mChildren) {
19936                            freezer.close();
19937                        }
19938                    }
19939                }
19940            }
19941        }
19942    }
19943
19944    /**
19945     * Verify that given package is currently frozen.
19946     */
19947    private void checkPackageFrozen(String packageName) {
19948        synchronized (mPackages) {
19949            if (!mFrozenPackages.contains(packageName)) {
19950                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19951            }
19952        }
19953    }
19954
19955    @Override
19956    public int movePackage(final String packageName, final String volumeUuid) {
19957        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19958
19959        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19960        final int moveId = mNextMoveId.getAndIncrement();
19961        mHandler.post(new Runnable() {
19962            @Override
19963            public void run() {
19964                try {
19965                    movePackageInternal(packageName, volumeUuid, moveId, user);
19966                } catch (PackageManagerException e) {
19967                    Slog.w(TAG, "Failed to move " + packageName, e);
19968                    mMoveCallbacks.notifyStatusChanged(moveId,
19969                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19970                }
19971            }
19972        });
19973        return moveId;
19974    }
19975
19976    private void movePackageInternal(final String packageName, final String volumeUuid,
19977            final int moveId, UserHandle user) throws PackageManagerException {
19978        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19979        final PackageManager pm = mContext.getPackageManager();
19980
19981        final boolean currentAsec;
19982        final String currentVolumeUuid;
19983        final File codeFile;
19984        final String installerPackageName;
19985        final String packageAbiOverride;
19986        final int appId;
19987        final String seinfo;
19988        final String label;
19989        final int targetSdkVersion;
19990        final PackageFreezer freezer;
19991        final int[] installedUserIds;
19992
19993        // reader
19994        synchronized (mPackages) {
19995            final PackageParser.Package pkg = mPackages.get(packageName);
19996            final PackageSetting ps = mSettings.mPackages.get(packageName);
19997            if (pkg == null || ps == null) {
19998                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
19999            }
20000
20001            if (pkg.applicationInfo.isSystemApp()) {
20002                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20003                        "Cannot move system application");
20004            }
20005
20006            if (pkg.applicationInfo.isExternalAsec()) {
20007                currentAsec = true;
20008                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20009            } else if (pkg.applicationInfo.isForwardLocked()) {
20010                currentAsec = true;
20011                currentVolumeUuid = "forward_locked";
20012            } else {
20013                currentAsec = false;
20014                currentVolumeUuid = ps.volumeUuid;
20015
20016                final File probe = new File(pkg.codePath);
20017                final File probeOat = new File(probe, "oat");
20018                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20019                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20020                            "Move only supported for modern cluster style installs");
20021                }
20022            }
20023
20024            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20025                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20026                        "Package already moved to " + volumeUuid);
20027            }
20028            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20029                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20030                        "Device admin cannot be moved");
20031            }
20032
20033            if (mFrozenPackages.contains(packageName)) {
20034                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20035                        "Failed to move already frozen package");
20036            }
20037
20038            codeFile = new File(pkg.codePath);
20039            installerPackageName = ps.installerPackageName;
20040            packageAbiOverride = ps.cpuAbiOverrideString;
20041            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20042            seinfo = pkg.applicationInfo.seinfo;
20043            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20044            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20045            freezer = freezePackage(packageName, "movePackageInternal");
20046            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20047        }
20048
20049        final Bundle extras = new Bundle();
20050        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20051        extras.putString(Intent.EXTRA_TITLE, label);
20052        mMoveCallbacks.notifyCreated(moveId, extras);
20053
20054        int installFlags;
20055        final boolean moveCompleteApp;
20056        final File measurePath;
20057
20058        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20059            installFlags = INSTALL_INTERNAL;
20060            moveCompleteApp = !currentAsec;
20061            measurePath = Environment.getDataAppDirectory(volumeUuid);
20062        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20063            installFlags = INSTALL_EXTERNAL;
20064            moveCompleteApp = false;
20065            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20066        } else {
20067            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20068            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20069                    || !volume.isMountedWritable()) {
20070                freezer.close();
20071                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20072                        "Move location not mounted private volume");
20073            }
20074
20075            Preconditions.checkState(!currentAsec);
20076
20077            installFlags = INSTALL_INTERNAL;
20078            moveCompleteApp = true;
20079            measurePath = Environment.getDataAppDirectory(volumeUuid);
20080        }
20081
20082        final PackageStats stats = new PackageStats(null, -1);
20083        synchronized (mInstaller) {
20084            for (int userId : installedUserIds) {
20085                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20086                    freezer.close();
20087                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20088                            "Failed to measure package size");
20089                }
20090            }
20091        }
20092
20093        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20094                + stats.dataSize);
20095
20096        final long startFreeBytes = measurePath.getFreeSpace();
20097        final long sizeBytes;
20098        if (moveCompleteApp) {
20099            sizeBytes = stats.codeSize + stats.dataSize;
20100        } else {
20101            sizeBytes = stats.codeSize;
20102        }
20103
20104        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20105            freezer.close();
20106            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20107                    "Not enough free space to move");
20108        }
20109
20110        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20111
20112        final CountDownLatch installedLatch = new CountDownLatch(1);
20113        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20114            @Override
20115            public void onUserActionRequired(Intent intent) throws RemoteException {
20116                throw new IllegalStateException();
20117            }
20118
20119            @Override
20120            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20121                    Bundle extras) throws RemoteException {
20122                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20123                        + PackageManager.installStatusToString(returnCode, msg));
20124
20125                installedLatch.countDown();
20126                freezer.close();
20127
20128                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20129                switch (status) {
20130                    case PackageInstaller.STATUS_SUCCESS:
20131                        mMoveCallbacks.notifyStatusChanged(moveId,
20132                                PackageManager.MOVE_SUCCEEDED);
20133                        break;
20134                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20135                        mMoveCallbacks.notifyStatusChanged(moveId,
20136                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20137                        break;
20138                    default:
20139                        mMoveCallbacks.notifyStatusChanged(moveId,
20140                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20141                        break;
20142                }
20143            }
20144        };
20145
20146        final MoveInfo move;
20147        if (moveCompleteApp) {
20148            // Kick off a thread to report progress estimates
20149            new Thread() {
20150                @Override
20151                public void run() {
20152                    while (true) {
20153                        try {
20154                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20155                                break;
20156                            }
20157                        } catch (InterruptedException ignored) {
20158                        }
20159
20160                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20161                        final int progress = 10 + (int) MathUtils.constrain(
20162                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20163                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20164                    }
20165                }
20166            }.start();
20167
20168            final String dataAppName = codeFile.getName();
20169            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20170                    dataAppName, appId, seinfo, targetSdkVersion);
20171        } else {
20172            move = null;
20173        }
20174
20175        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20176
20177        final Message msg = mHandler.obtainMessage(INIT_COPY);
20178        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20179        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20180                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20181                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20182        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20183        msg.obj = params;
20184
20185        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20186                System.identityHashCode(msg.obj));
20187        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20188                System.identityHashCode(msg.obj));
20189
20190        mHandler.sendMessage(msg);
20191    }
20192
20193    @Override
20194    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20195        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20196
20197        final int realMoveId = mNextMoveId.getAndIncrement();
20198        final Bundle extras = new Bundle();
20199        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20200        mMoveCallbacks.notifyCreated(realMoveId, extras);
20201
20202        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20203            @Override
20204            public void onCreated(int moveId, Bundle extras) {
20205                // Ignored
20206            }
20207
20208            @Override
20209            public void onStatusChanged(int moveId, int status, long estMillis) {
20210                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20211            }
20212        };
20213
20214        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20215        storage.setPrimaryStorageUuid(volumeUuid, callback);
20216        return realMoveId;
20217    }
20218
20219    @Override
20220    public int getMoveStatus(int moveId) {
20221        mContext.enforceCallingOrSelfPermission(
20222                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20223        return mMoveCallbacks.mLastStatus.get(moveId);
20224    }
20225
20226    @Override
20227    public void registerMoveCallback(IPackageMoveObserver callback) {
20228        mContext.enforceCallingOrSelfPermission(
20229                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20230        mMoveCallbacks.register(callback);
20231    }
20232
20233    @Override
20234    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20235        mContext.enforceCallingOrSelfPermission(
20236                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20237        mMoveCallbacks.unregister(callback);
20238    }
20239
20240    @Override
20241    public boolean setInstallLocation(int loc) {
20242        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20243                null);
20244        if (getInstallLocation() == loc) {
20245            return true;
20246        }
20247        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20248                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20249            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20250                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20251            return true;
20252        }
20253        return false;
20254   }
20255
20256    @Override
20257    public int getInstallLocation() {
20258        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20259                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20260                PackageHelper.APP_INSTALL_AUTO);
20261    }
20262
20263    /** Called by UserManagerService */
20264    void cleanUpUser(UserManagerService userManager, int userHandle) {
20265        synchronized (mPackages) {
20266            mDirtyUsers.remove(userHandle);
20267            mUserNeedsBadging.delete(userHandle);
20268            mSettings.removeUserLPw(userHandle);
20269            mPendingBroadcasts.remove(userHandle);
20270            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20271            removeUnusedPackagesLPw(userManager, userHandle);
20272        }
20273    }
20274
20275    /**
20276     * We're removing userHandle and would like to remove any downloaded packages
20277     * that are no longer in use by any other user.
20278     * @param userHandle the user being removed
20279     */
20280    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20281        final boolean DEBUG_CLEAN_APKS = false;
20282        int [] users = userManager.getUserIds();
20283        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20284        while (psit.hasNext()) {
20285            PackageSetting ps = psit.next();
20286            if (ps.pkg == null) {
20287                continue;
20288            }
20289            final String packageName = ps.pkg.packageName;
20290            // Skip over if system app
20291            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20292                continue;
20293            }
20294            if (DEBUG_CLEAN_APKS) {
20295                Slog.i(TAG, "Checking package " + packageName);
20296            }
20297            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20298            if (keep) {
20299                if (DEBUG_CLEAN_APKS) {
20300                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20301                }
20302            } else {
20303                for (int i = 0; i < users.length; i++) {
20304                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20305                        keep = true;
20306                        if (DEBUG_CLEAN_APKS) {
20307                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20308                                    + users[i]);
20309                        }
20310                        break;
20311                    }
20312                }
20313            }
20314            if (!keep) {
20315                if (DEBUG_CLEAN_APKS) {
20316                    Slog.i(TAG, "  Removing package " + packageName);
20317                }
20318                mHandler.post(new Runnable() {
20319                    public void run() {
20320                        deletePackageX(packageName, userHandle, 0);
20321                    } //end run
20322                });
20323            }
20324        }
20325    }
20326
20327    /** Called by UserManagerService */
20328    void createNewUser(int userId) {
20329        synchronized (mInstallLock) {
20330            mSettings.createNewUserLI(this, mInstaller, userId);
20331        }
20332        synchronized (mPackages) {
20333            scheduleWritePackageRestrictionsLocked(userId);
20334            scheduleWritePackageListLocked(userId);
20335            applyFactoryDefaultBrowserLPw(userId);
20336            primeDomainVerificationsLPw(userId);
20337        }
20338    }
20339
20340    void onNewUserCreated(final int userId) {
20341        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20342        // If permission review for legacy apps is required, we represent
20343        // dagerous permissions for such apps as always granted runtime
20344        // permissions to keep per user flag state whether review is needed.
20345        // Hence, if a new user is added we have to propagate dangerous
20346        // permission grants for these legacy apps.
20347        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20348            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20349                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20350        }
20351    }
20352
20353    @Override
20354    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20355        mContext.enforceCallingOrSelfPermission(
20356                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20357                "Only package verification agents can read the verifier device identity");
20358
20359        synchronized (mPackages) {
20360            return mSettings.getVerifierDeviceIdentityLPw();
20361        }
20362    }
20363
20364    @Override
20365    public void setPermissionEnforced(String permission, boolean enforced) {
20366        // TODO: Now that we no longer change GID for storage, this should to away.
20367        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20368                "setPermissionEnforced");
20369        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20370            synchronized (mPackages) {
20371                if (mSettings.mReadExternalStorageEnforced == null
20372                        || mSettings.mReadExternalStorageEnforced != enforced) {
20373                    mSettings.mReadExternalStorageEnforced = enforced;
20374                    mSettings.writeLPr();
20375                }
20376            }
20377            // kill any non-foreground processes so we restart them and
20378            // grant/revoke the GID.
20379            final IActivityManager am = ActivityManagerNative.getDefault();
20380            if (am != null) {
20381                final long token = Binder.clearCallingIdentity();
20382                try {
20383                    am.killProcessesBelowForeground("setPermissionEnforcement");
20384                } catch (RemoteException e) {
20385                } finally {
20386                    Binder.restoreCallingIdentity(token);
20387                }
20388            }
20389        } else {
20390            throw new IllegalArgumentException("No selective enforcement for " + permission);
20391        }
20392    }
20393
20394    @Override
20395    @Deprecated
20396    public boolean isPermissionEnforced(String permission) {
20397        return true;
20398    }
20399
20400    @Override
20401    public boolean isStorageLow() {
20402        final long token = Binder.clearCallingIdentity();
20403        try {
20404            final DeviceStorageMonitorInternal
20405                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20406            if (dsm != null) {
20407                return dsm.isMemoryLow();
20408            } else {
20409                return false;
20410            }
20411        } finally {
20412            Binder.restoreCallingIdentity(token);
20413        }
20414    }
20415
20416    @Override
20417    public IPackageInstaller getPackageInstaller() {
20418        return mInstallerService;
20419    }
20420
20421    private boolean userNeedsBadging(int userId) {
20422        int index = mUserNeedsBadging.indexOfKey(userId);
20423        if (index < 0) {
20424            final UserInfo userInfo;
20425            final long token = Binder.clearCallingIdentity();
20426            try {
20427                userInfo = sUserManager.getUserInfo(userId);
20428            } finally {
20429                Binder.restoreCallingIdentity(token);
20430            }
20431            final boolean b;
20432            if (userInfo != null && userInfo.isManagedProfile()) {
20433                b = true;
20434            } else {
20435                b = false;
20436            }
20437            mUserNeedsBadging.put(userId, b);
20438            return b;
20439        }
20440        return mUserNeedsBadging.valueAt(index);
20441    }
20442
20443    @Override
20444    public KeySet getKeySetByAlias(String packageName, String alias) {
20445        if (packageName == null || alias == null) {
20446            return null;
20447        }
20448        synchronized(mPackages) {
20449            final PackageParser.Package pkg = mPackages.get(packageName);
20450            if (pkg == null) {
20451                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20452                throw new IllegalArgumentException("Unknown package: " + packageName);
20453            }
20454            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20455            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20456        }
20457    }
20458
20459    @Override
20460    public KeySet getSigningKeySet(String packageName) {
20461        if (packageName == null) {
20462            return null;
20463        }
20464        synchronized(mPackages) {
20465            final PackageParser.Package pkg = mPackages.get(packageName);
20466            if (pkg == null) {
20467                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20468                throw new IllegalArgumentException("Unknown package: " + packageName);
20469            }
20470            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20471                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20472                throw new SecurityException("May not access signing KeySet of other apps.");
20473            }
20474            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20475            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20476        }
20477    }
20478
20479    @Override
20480    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20481        if (packageName == null || ks == null) {
20482            return false;
20483        }
20484        synchronized(mPackages) {
20485            final PackageParser.Package pkg = mPackages.get(packageName);
20486            if (pkg == null) {
20487                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20488                throw new IllegalArgumentException("Unknown package: " + packageName);
20489            }
20490            IBinder ksh = ks.getToken();
20491            if (ksh instanceof KeySetHandle) {
20492                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20493                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20494            }
20495            return false;
20496        }
20497    }
20498
20499    @Override
20500    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20501        if (packageName == null || ks == null) {
20502            return false;
20503        }
20504        synchronized(mPackages) {
20505            final PackageParser.Package pkg = mPackages.get(packageName);
20506            if (pkg == null) {
20507                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20508                throw new IllegalArgumentException("Unknown package: " + packageName);
20509            }
20510            IBinder ksh = ks.getToken();
20511            if (ksh instanceof KeySetHandle) {
20512                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20513                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20514            }
20515            return false;
20516        }
20517    }
20518
20519    private void deletePackageIfUnusedLPr(final String packageName) {
20520        PackageSetting ps = mSettings.mPackages.get(packageName);
20521        if (ps == null) {
20522            return;
20523        }
20524        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20525            // TODO Implement atomic delete if package is unused
20526            // It is currently possible that the package will be deleted even if it is installed
20527            // after this method returns.
20528            mHandler.post(new Runnable() {
20529                public void run() {
20530                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20531                }
20532            });
20533        }
20534    }
20535
20536    /**
20537     * Check and throw if the given before/after packages would be considered a
20538     * downgrade.
20539     */
20540    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20541            throws PackageManagerException {
20542        if (after.versionCode < before.mVersionCode) {
20543            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20544                    "Update version code " + after.versionCode + " is older than current "
20545                    + before.mVersionCode);
20546        } else if (after.versionCode == before.mVersionCode) {
20547            if (after.baseRevisionCode < before.baseRevisionCode) {
20548                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20549                        "Update base revision code " + after.baseRevisionCode
20550                        + " is older than current " + before.baseRevisionCode);
20551            }
20552
20553            if (!ArrayUtils.isEmpty(after.splitNames)) {
20554                for (int i = 0; i < after.splitNames.length; i++) {
20555                    final String splitName = after.splitNames[i];
20556                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20557                    if (j != -1) {
20558                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20559                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20560                                    "Update split " + splitName + " revision code "
20561                                    + after.splitRevisionCodes[i] + " is older than current "
20562                                    + before.splitRevisionCodes[j]);
20563                        }
20564                    }
20565                }
20566            }
20567        }
20568    }
20569
20570    private static class MoveCallbacks extends Handler {
20571        private static final int MSG_CREATED = 1;
20572        private static final int MSG_STATUS_CHANGED = 2;
20573
20574        private final RemoteCallbackList<IPackageMoveObserver>
20575                mCallbacks = new RemoteCallbackList<>();
20576
20577        private final SparseIntArray mLastStatus = new SparseIntArray();
20578
20579        public MoveCallbacks(Looper looper) {
20580            super(looper);
20581        }
20582
20583        public void register(IPackageMoveObserver callback) {
20584            mCallbacks.register(callback);
20585        }
20586
20587        public void unregister(IPackageMoveObserver callback) {
20588            mCallbacks.unregister(callback);
20589        }
20590
20591        @Override
20592        public void handleMessage(Message msg) {
20593            final SomeArgs args = (SomeArgs) msg.obj;
20594            final int n = mCallbacks.beginBroadcast();
20595            for (int i = 0; i < n; i++) {
20596                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20597                try {
20598                    invokeCallback(callback, msg.what, args);
20599                } catch (RemoteException ignored) {
20600                }
20601            }
20602            mCallbacks.finishBroadcast();
20603            args.recycle();
20604        }
20605
20606        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20607                throws RemoteException {
20608            switch (what) {
20609                case MSG_CREATED: {
20610                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20611                    break;
20612                }
20613                case MSG_STATUS_CHANGED: {
20614                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20615                    break;
20616                }
20617            }
20618        }
20619
20620        private void notifyCreated(int moveId, Bundle extras) {
20621            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20622
20623            final SomeArgs args = SomeArgs.obtain();
20624            args.argi1 = moveId;
20625            args.arg2 = extras;
20626            obtainMessage(MSG_CREATED, args).sendToTarget();
20627        }
20628
20629        private void notifyStatusChanged(int moveId, int status) {
20630            notifyStatusChanged(moveId, status, -1);
20631        }
20632
20633        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20634            Slog.v(TAG, "Move " + moveId + " status " + status);
20635
20636            final SomeArgs args = SomeArgs.obtain();
20637            args.argi1 = moveId;
20638            args.argi2 = status;
20639            args.arg3 = estMillis;
20640            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20641
20642            synchronized (mLastStatus) {
20643                mLastStatus.put(moveId, status);
20644            }
20645        }
20646    }
20647
20648    private final static class OnPermissionChangeListeners extends Handler {
20649        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20650
20651        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20652                new RemoteCallbackList<>();
20653
20654        public OnPermissionChangeListeners(Looper looper) {
20655            super(looper);
20656        }
20657
20658        @Override
20659        public void handleMessage(Message msg) {
20660            switch (msg.what) {
20661                case MSG_ON_PERMISSIONS_CHANGED: {
20662                    final int uid = msg.arg1;
20663                    handleOnPermissionsChanged(uid);
20664                } break;
20665            }
20666        }
20667
20668        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20669            mPermissionListeners.register(listener);
20670
20671        }
20672
20673        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20674            mPermissionListeners.unregister(listener);
20675        }
20676
20677        public void onPermissionsChanged(int uid) {
20678            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20679                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20680            }
20681        }
20682
20683        private void handleOnPermissionsChanged(int uid) {
20684            final int count = mPermissionListeners.beginBroadcast();
20685            try {
20686                for (int i = 0; i < count; i++) {
20687                    IOnPermissionsChangeListener callback = mPermissionListeners
20688                            .getBroadcastItem(i);
20689                    try {
20690                        callback.onPermissionsChanged(uid);
20691                    } catch (RemoteException e) {
20692                        Log.e(TAG, "Permission listener is dead", e);
20693                    }
20694                }
20695            } finally {
20696                mPermissionListeners.finishBroadcast();
20697            }
20698        }
20699    }
20700
20701    private class PackageManagerInternalImpl extends PackageManagerInternal {
20702        @Override
20703        public void setLocationPackagesProvider(PackagesProvider provider) {
20704            synchronized (mPackages) {
20705                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20706            }
20707        }
20708
20709        @Override
20710        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20711            synchronized (mPackages) {
20712                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20713            }
20714        }
20715
20716        @Override
20717        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20718            synchronized (mPackages) {
20719                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20720            }
20721        }
20722
20723        @Override
20724        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20725            synchronized (mPackages) {
20726                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20727            }
20728        }
20729
20730        @Override
20731        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20732            synchronized (mPackages) {
20733                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20734            }
20735        }
20736
20737        @Override
20738        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20739            synchronized (mPackages) {
20740                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20741            }
20742        }
20743
20744        @Override
20745        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20746            synchronized (mPackages) {
20747                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20748                        packageName, userId);
20749            }
20750        }
20751
20752        @Override
20753        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20754            synchronized (mPackages) {
20755                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20756                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20757                        packageName, userId);
20758            }
20759        }
20760
20761        @Override
20762        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20763            synchronized (mPackages) {
20764                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20765                        packageName, userId);
20766            }
20767        }
20768
20769        @Override
20770        public void setKeepUninstalledPackages(final List<String> packageList) {
20771            Preconditions.checkNotNull(packageList);
20772            List<String> removedFromList = null;
20773            synchronized (mPackages) {
20774                if (mKeepUninstalledPackages != null) {
20775                    final int packagesCount = mKeepUninstalledPackages.size();
20776                    for (int i = 0; i < packagesCount; i++) {
20777                        String oldPackage = mKeepUninstalledPackages.get(i);
20778                        if (packageList != null && packageList.contains(oldPackage)) {
20779                            continue;
20780                        }
20781                        if (removedFromList == null) {
20782                            removedFromList = new ArrayList<>();
20783                        }
20784                        removedFromList.add(oldPackage);
20785                    }
20786                }
20787                mKeepUninstalledPackages = new ArrayList<>(packageList);
20788                if (removedFromList != null) {
20789                    final int removedCount = removedFromList.size();
20790                    for (int i = 0; i < removedCount; i++) {
20791                        deletePackageIfUnusedLPr(removedFromList.get(i));
20792                    }
20793                }
20794            }
20795        }
20796
20797        @Override
20798        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20799            synchronized (mPackages) {
20800                // If we do not support permission review, done.
20801                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20802                    return false;
20803                }
20804
20805                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20806                if (packageSetting == null) {
20807                    return false;
20808                }
20809
20810                // Permission review applies only to apps not supporting the new permission model.
20811                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20812                    return false;
20813                }
20814
20815                // Legacy apps have the permission and get user consent on launch.
20816                PermissionsState permissionsState = packageSetting.getPermissionsState();
20817                return permissionsState.isPermissionReviewRequired(userId);
20818            }
20819        }
20820
20821        @Override
20822        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20823            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20824        }
20825
20826        @Override
20827        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20828                int userId) {
20829            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20830        }
20831
20832        @Override
20833        public void setDeviceAndProfileOwnerPackages(
20834                int deviceOwnerUserId, String deviceOwnerPackage,
20835                SparseArray<String> profileOwnerPackages) {
20836            mProtectedPackages.setDeviceAndProfileOwnerPackages(
20837                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
20838        }
20839
20840        @Override
20841        public boolean isPackageDataProtected(int userId, String packageName) {
20842            return mProtectedPackages.isPackageDataProtected(userId, packageName);
20843        }
20844    }
20845
20846    @Override
20847    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20848        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20849        synchronized (mPackages) {
20850            final long identity = Binder.clearCallingIdentity();
20851            try {
20852                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20853                        packageNames, userId);
20854            } finally {
20855                Binder.restoreCallingIdentity(identity);
20856            }
20857        }
20858    }
20859
20860    private static void enforceSystemOrPhoneCaller(String tag) {
20861        int callingUid = Binder.getCallingUid();
20862        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20863            throw new SecurityException(
20864                    "Cannot call " + tag + " from UID " + callingUid);
20865        }
20866    }
20867
20868    boolean isHistoricalPackageUsageAvailable() {
20869        return mPackageUsage.isHistoricalPackageUsageAvailable();
20870    }
20871
20872    /**
20873     * Return a <b>copy</b> of the collection of packages known to the package manager.
20874     * @return A copy of the values of mPackages.
20875     */
20876    Collection<PackageParser.Package> getPackages() {
20877        synchronized (mPackages) {
20878            return new ArrayList<>(mPackages.values());
20879        }
20880    }
20881
20882    /**
20883     * Logs process start information (including base APK hash) to the security log.
20884     * @hide
20885     */
20886    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20887            String apkFile, int pid) {
20888        if (!SecurityLog.isLoggingEnabled()) {
20889            return;
20890        }
20891        Bundle data = new Bundle();
20892        data.putLong("startTimestamp", System.currentTimeMillis());
20893        data.putString("processName", processName);
20894        data.putInt("uid", uid);
20895        data.putString("seinfo", seinfo);
20896        data.putString("apkFile", apkFile);
20897        data.putInt("pid", pid);
20898        Message msg = mProcessLoggingHandler.obtainMessage(
20899                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20900        msg.setData(data);
20901        mProcessLoggingHandler.sendMessage(msg);
20902    }
20903
20904    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
20905        return mCompilerStats.getPackageStats(pkgName);
20906    }
20907
20908    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
20909        return getOrCreateCompilerPackageStats(pkg.packageName);
20910    }
20911
20912    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
20913        return mCompilerStats.getOrCreatePackageStats(pkgName);
20914    }
20915
20916    public void deleteCompilerPackageStats(String pkgName) {
20917        mCompilerStats.deletePackageStats(pkgName);
20918    }
20919}
20920