PackageManagerService.java revision cd029da32165f4a348431d825d2bbaa46282710f
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55import static android.content.pm.PackageManager.INSTALL_INTERNAL;
56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
62import static android.content.pm.PackageManager.MATCH_ALL;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
75import static android.content.pm.PackageManager.PERMISSION_DENIED;
76import static android.content.pm.PackageManager.PERMISSION_GRANTED;
77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
78import static android.content.pm.PackageParser.isApkFile;
79import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
80import static android.system.OsConstants.O_CREAT;
81import static android.system.OsConstants.O_RDWR;
82
83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
85import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
86import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
87import static com.android.internal.util.ArrayUtils.appendInt;
88import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
89import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
92import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
93import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter;
97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
100
101import android.Manifest;
102import android.annotation.NonNull;
103import android.annotation.Nullable;
104import android.annotation.UserIdInt;
105import android.app.ActivityManager;
106import android.app.ActivityManagerNative;
107import android.app.IActivityManager;
108import android.app.ResourcesManager;
109import android.app.admin.IDevicePolicyManager;
110import android.app.admin.SecurityLog;
111import android.app.backup.IBackupManager;
112import android.content.BroadcastReceiver;
113import android.content.ComponentName;
114import android.content.Context;
115import android.content.IIntentReceiver;
116import android.content.Intent;
117import android.content.IntentFilter;
118import android.content.IntentSender;
119import android.content.IntentSender.SendIntentException;
120import android.content.ServiceConnection;
121import android.content.pm.ActivityInfo;
122import android.content.pm.ApplicationInfo;
123import android.content.pm.AppsQueryHelper;
124import android.content.pm.ComponentInfo;
125import android.content.pm.EphemeralApplicationInfo;
126import android.content.pm.EphemeralResolveInfo;
127import android.content.pm.EphemeralResolveInfo.EphemeralDigest;
128import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
129import android.content.pm.FeatureInfo;
130import android.content.pm.IOnPermissionsChangeListener;
131import android.content.pm.IPackageDataObserver;
132import android.content.pm.IPackageDeleteObserver;
133import android.content.pm.IPackageDeleteObserver2;
134import android.content.pm.IPackageInstallObserver2;
135import android.content.pm.IPackageInstaller;
136import android.content.pm.IPackageManager;
137import android.content.pm.IPackageMoveObserver;
138import android.content.pm.IPackageStatsObserver;
139import android.content.pm.InstrumentationInfo;
140import android.content.pm.IntentFilterVerificationInfo;
141import android.content.pm.KeySet;
142import android.content.pm.PackageCleanItem;
143import android.content.pm.PackageInfo;
144import android.content.pm.PackageInfoLite;
145import android.content.pm.PackageInstaller;
146import android.content.pm.PackageManager;
147import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
148import android.content.pm.PackageManagerInternal;
149import android.content.pm.PackageParser;
150import android.content.pm.PackageParser.ActivityIntentInfo;
151import android.content.pm.PackageParser.PackageLite;
152import android.content.pm.PackageParser.PackageParserException;
153import android.content.pm.PackageStats;
154import android.content.pm.PackageUserState;
155import android.content.pm.ParceledListSlice;
156import android.content.pm.PermissionGroupInfo;
157import android.content.pm.PermissionInfo;
158import android.content.pm.ProviderInfo;
159import android.content.pm.ResolveInfo;
160import android.content.pm.ServiceInfo;
161import android.content.pm.Signature;
162import android.content.pm.UserInfo;
163import android.content.pm.VerifierDeviceIdentity;
164import android.content.pm.VerifierInfo;
165import android.content.res.Resources;
166import android.graphics.Bitmap;
167import android.hardware.display.DisplayManager;
168import android.net.Uri;
169import android.os.Binder;
170import android.os.Build;
171import android.os.Bundle;
172import android.os.Debug;
173import android.os.Environment;
174import android.os.Environment.UserEnvironment;
175import android.os.FileUtils;
176import android.os.Handler;
177import android.os.IBinder;
178import android.os.Looper;
179import android.os.Message;
180import android.os.Parcel;
181import android.os.ParcelFileDescriptor;
182import android.os.Process;
183import android.os.RemoteCallbackList;
184import android.os.RemoteException;
185import android.os.ResultReceiver;
186import android.os.SELinux;
187import android.os.ServiceManager;
188import android.os.SystemClock;
189import android.os.SystemProperties;
190import android.os.Trace;
191import android.os.UserHandle;
192import android.os.UserManager;
193import android.os.UserManagerInternal;
194import android.os.storage.IMountService;
195import android.os.storage.MountServiceInternal;
196import android.os.storage.StorageEventListener;
197import android.os.storage.StorageManager;
198import android.os.storage.VolumeInfo;
199import android.os.storage.VolumeRecord;
200import android.provider.Settings.Global;
201import android.security.KeyStore;
202import android.security.SystemKeyStore;
203import android.system.ErrnoException;
204import android.system.Os;
205import android.text.TextUtils;
206import android.text.format.DateUtils;
207import android.util.ArrayMap;
208import android.util.ArraySet;
209import android.util.DisplayMetrics;
210import android.util.EventLog;
211import android.util.ExceptionUtils;
212import android.util.Log;
213import android.util.LogPrinter;
214import android.util.MathUtils;
215import android.util.PrintStreamPrinter;
216import android.util.Slog;
217import android.util.SparseArray;
218import android.util.SparseBooleanArray;
219import android.util.SparseIntArray;
220import android.util.Xml;
221import android.util.jar.StrictJarFile;
222import android.view.Display;
223
224import com.android.internal.R;
225import com.android.internal.annotations.GuardedBy;
226import com.android.internal.app.IMediaContainerService;
227import com.android.internal.app.ResolverActivity;
228import com.android.internal.content.NativeLibraryHelper;
229import com.android.internal.content.PackageHelper;
230import com.android.internal.logging.MetricsLogger;
231import com.android.internal.os.IParcelFileDescriptorFactory;
232import com.android.internal.os.InstallerConnection.InstallerException;
233import com.android.internal.os.SomeArgs;
234import com.android.internal.os.Zygote;
235import com.android.internal.telephony.CarrierAppUtils;
236import com.android.internal.util.ArrayUtils;
237import com.android.internal.util.FastPrintWriter;
238import com.android.internal.util.FastXmlSerializer;
239import com.android.internal.util.IndentingPrintWriter;
240import com.android.internal.util.Preconditions;
241import com.android.internal.util.XmlUtils;
242import com.android.server.AttributeCache;
243import com.android.server.EventLogTags;
244import com.android.server.FgThread;
245import com.android.server.IntentResolver;
246import com.android.server.LocalServices;
247import com.android.server.ServiceThread;
248import com.android.server.SystemConfig;
249import com.android.server.Watchdog;
250import com.android.server.net.NetworkPolicyManagerInternal;
251import com.android.server.pm.PermissionsState.PermissionState;
252import com.android.server.pm.Settings.DatabaseVersion;
253import com.android.server.pm.Settings.VersionInfo;
254import com.android.server.storage.DeviceStorageMonitorInternal;
255
256import dalvik.system.CloseGuard;
257import dalvik.system.DexFile;
258import dalvik.system.VMRuntime;
259
260import libcore.io.IoUtils;
261import libcore.util.EmptyArray;
262
263import org.xmlpull.v1.XmlPullParser;
264import org.xmlpull.v1.XmlPullParserException;
265import org.xmlpull.v1.XmlSerializer;
266
267import java.io.BufferedOutputStream;
268import java.io.BufferedReader;
269import java.io.ByteArrayInputStream;
270import java.io.ByteArrayOutputStream;
271import java.io.File;
272import java.io.FileDescriptor;
273import java.io.FileInputStream;
274import java.io.FileNotFoundException;
275import java.io.FileOutputStream;
276import java.io.FileReader;
277import java.io.FilenameFilter;
278import java.io.IOException;
279import java.io.PrintWriter;
280import java.nio.charset.StandardCharsets;
281import java.security.DigestInputStream;
282import java.security.MessageDigest;
283import java.security.NoSuchAlgorithmException;
284import java.security.PublicKey;
285import java.security.cert.Certificate;
286import java.security.cert.CertificateEncodingException;
287import java.security.cert.CertificateException;
288import java.text.SimpleDateFormat;
289import java.util.ArrayList;
290import java.util.Arrays;
291import java.util.Collection;
292import java.util.Collections;
293import java.util.Comparator;
294import java.util.Date;
295import java.util.HashSet;
296import java.util.Iterator;
297import java.util.List;
298import java.util.Map;
299import java.util.Objects;
300import java.util.Set;
301import java.util.concurrent.CountDownLatch;
302import java.util.concurrent.TimeUnit;
303import java.util.concurrent.atomic.AtomicBoolean;
304import java.util.concurrent.atomic.AtomicInteger;
305
306/**
307 * Keep track of all those APKs everywhere.
308 * <p>
309 * Internally there are two important locks:
310 * <ul>
311 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
312 * and other related state. It is a fine-grained lock that should only be held
313 * momentarily, as it's one of the most contended locks in the system.
314 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
315 * operations typically involve heavy lifting of application data on disk. Since
316 * {@code installd} is single-threaded, and it's operations can often be slow,
317 * this lock should never be acquired while already holding {@link #mPackages}.
318 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
319 * holding {@link #mInstallLock}.
320 * </ul>
321 * Many internal methods rely on the caller to hold the appropriate locks, and
322 * this contract is expressed through method name suffixes:
323 * <ul>
324 * <li>fooLI(): the caller must hold {@link #mInstallLock}
325 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
326 * being modified must be frozen
327 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
328 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
329 * </ul>
330 * <p>
331 * Because this class is very central to the platform's security; please run all
332 * CTS and unit tests whenever making modifications:
333 *
334 * <pre>
335 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
336 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
337 * </pre>
338 */
339public class PackageManagerService extends IPackageManager.Stub {
340    static final String TAG = "PackageManager";
341    static final boolean DEBUG_SETTINGS = false;
342    static final boolean DEBUG_PREFERRED = false;
343    static final boolean DEBUG_UPGRADE = false;
344    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
345    private static final boolean DEBUG_BACKUP = false;
346    private static final boolean DEBUG_INSTALL = false;
347    private static final boolean DEBUG_REMOVE = false;
348    private static final boolean DEBUG_BROADCASTS = false;
349    private static final boolean DEBUG_SHOW_INFO = false;
350    private static final boolean DEBUG_PACKAGE_INFO = false;
351    private static final boolean DEBUG_INTENT_MATCHING = false;
352    private static final boolean DEBUG_PACKAGE_SCANNING = false;
353    private static final boolean DEBUG_VERIFY = false;
354    private static final boolean DEBUG_FILTERS = false;
355
356    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
357    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
358    // user, but by default initialize to this.
359    static final boolean DEBUG_DEXOPT = false;
360
361    private static final boolean DEBUG_ABI_SELECTION = false;
362    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
363    private static final boolean DEBUG_TRIAGED_MISSING = false;
364    private static final boolean DEBUG_APP_DATA = false;
365
366    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
367
368    private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE;
369
370    private static final int RADIO_UID = Process.PHONE_UID;
371    private static final int LOG_UID = Process.LOG_UID;
372    private static final int NFC_UID = Process.NFC_UID;
373    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
374    private static final int SHELL_UID = Process.SHELL_UID;
375
376    // Cap the size of permission trees that 3rd party apps can define
377    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
378
379    // Suffix used during package installation when copying/moving
380    // package apks to install directory.
381    private static final String INSTALL_PACKAGE_SUFFIX = "-";
382
383    static final int SCAN_NO_DEX = 1<<1;
384    static final int SCAN_FORCE_DEX = 1<<2;
385    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
386    static final int SCAN_NEW_INSTALL = 1<<4;
387    static final int SCAN_NO_PATHS = 1<<5;
388    static final int SCAN_UPDATE_TIME = 1<<6;
389    static final int SCAN_DEFER_DEX = 1<<7;
390    static final int SCAN_BOOTING = 1<<8;
391    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
392    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
393    static final int SCAN_REPLACING = 1<<11;
394    static final int SCAN_REQUIRE_KNOWN = 1<<12;
395    static final int SCAN_MOVE = 1<<13;
396    static final int SCAN_INITIAL = 1<<14;
397    static final int SCAN_CHECK_ONLY = 1<<15;
398    static final int SCAN_DONT_KILL_APP = 1<<17;
399    static final int SCAN_IGNORE_FROZEN = 1<<18;
400
401    static final int REMOVE_CHATTY = 1<<16;
402
403    private static final int[] EMPTY_INT_ARRAY = new int[0];
404
405    /**
406     * Timeout (in milliseconds) after which the watchdog should declare that
407     * our handler thread is wedged.  The usual default for such things is one
408     * minute but we sometimes do very lengthy I/O operations on this thread,
409     * such as installing multi-gigabyte applications, so ours needs to be longer.
410     */
411    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
412
413    /**
414     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
415     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
416     * settings entry if available, otherwise we use the hardcoded default.  If it's been
417     * more than this long since the last fstrim, we force one during the boot sequence.
418     *
419     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
420     * one gets run at the next available charging+idle time.  This final mandatory
421     * no-fstrim check kicks in only of the other scheduling criteria is never met.
422     */
423    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
424
425    /**
426     * Whether verification is enabled by default.
427     */
428    private static final boolean DEFAULT_VERIFY_ENABLE = true;
429
430    /**
431     * The default maximum time to wait for the verification agent to return in
432     * milliseconds.
433     */
434    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
435
436    /**
437     * The default response for package verification timeout.
438     *
439     * This can be either PackageManager.VERIFICATION_ALLOW or
440     * PackageManager.VERIFICATION_REJECT.
441     */
442    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
443
444    static final String PLATFORM_PACKAGE_NAME = "android";
445
446    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
447
448    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
449            DEFAULT_CONTAINER_PACKAGE,
450            "com.android.defcontainer.DefaultContainerService");
451
452    private static final String KILL_APP_REASON_GIDS_CHANGED =
453            "permission grant or revoke changed gids";
454
455    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
456            "permissions revoked";
457
458    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
459
460    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
461
462    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000;
463    private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5;
464
465    /** Permission grant: not grant the permission. */
466    private static final int GRANT_DENIED = 1;
467
468    /** Permission grant: grant the permission as an install permission. */
469    private static final int GRANT_INSTALL = 2;
470
471    /** Permission grant: grant the permission as a runtime one. */
472    private static final int GRANT_RUNTIME = 3;
473
474    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
475    private static final int GRANT_UPGRADE = 4;
476
477    /** Canonical intent used to identify what counts as a "web browser" app */
478    private static final Intent sBrowserIntent;
479    static {
480        sBrowserIntent = new Intent();
481        sBrowserIntent.setAction(Intent.ACTION_VIEW);
482        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
483        sBrowserIntent.setData(Uri.parse("http:"));
484    }
485
486    /**
487     * The set of all protected actions [i.e. those actions for which a high priority
488     * intent filter is disallowed].
489     */
490    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
491    static {
492        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
493        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
494        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
495        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
496    }
497
498    // Compilation reasons.
499    public static final int REASON_FIRST_BOOT = 0;
500    public static final int REASON_BOOT = 1;
501    public static final int REASON_INSTALL = 2;
502    public static final int REASON_BACKGROUND_DEXOPT = 3;
503    public static final int REASON_AB_OTA = 4;
504    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
505    public static final int REASON_SHARED_APK = 6;
506    public static final int REASON_FORCED_DEXOPT = 7;
507    public static final int REASON_CORE_APP = 8;
508
509    public static final int REASON_LAST = REASON_CORE_APP;
510
511    /** Special library name that skips shared libraries check during compilation. */
512    private static final String SKIP_SHARED_LIBRARY_CHECK = "&";
513
514    final ServiceThread mHandlerThread;
515
516    final PackageHandler mHandler;
517
518    private final ProcessLoggingHandler mProcessLoggingHandler;
519
520    /**
521     * Messages for {@link #mHandler} that need to wait for system ready before
522     * being dispatched.
523     */
524    private ArrayList<Message> mPostSystemReadyMessages;
525
526    final int mSdkVersion = Build.VERSION.SDK_INT;
527
528    final Context mContext;
529    final boolean mFactoryTest;
530    final boolean mOnlyCore;
531    final DisplayMetrics mMetrics;
532    final int mDefParseFlags;
533    final String[] mSeparateProcesses;
534    final boolean mIsUpgrade;
535    final boolean mIsPreNUpgrade;
536
537    /** The location for ASEC container files on internal storage. */
538    final String mAsecInternalPath;
539
540    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
541    // LOCK HELD.  Can be called with mInstallLock held.
542    @GuardedBy("mInstallLock")
543    final Installer mInstaller;
544
545    /** Directory where installed third-party apps stored */
546    final File mAppInstallDir;
547    final File mEphemeralInstallDir;
548
549    /**
550     * Directory to which applications installed internally have their
551     * 32 bit native libraries copied.
552     */
553    private File mAppLib32InstallDir;
554
555    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
556    // apps.
557    final File mDrmAppPrivateInstallDir;
558
559    // ----------------------------------------------------------------
560
561    // Lock for state used when installing and doing other long running
562    // operations.  Methods that must be called with this lock held have
563    // the suffix "LI".
564    final Object mInstallLock = new Object();
565
566    // ----------------------------------------------------------------
567
568    // Keys are String (package name), values are Package.  This also serves
569    // as the lock for the global state.  Methods that must be called with
570    // this lock held have the prefix "LP".
571    @GuardedBy("mPackages")
572    final ArrayMap<String, PackageParser.Package> mPackages =
573            new ArrayMap<String, PackageParser.Package>();
574
575    final ArrayMap<String, Set<String>> mKnownCodebase =
576            new ArrayMap<String, Set<String>>();
577
578    // Tracks available target package names -> overlay package paths.
579    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
580        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
581
582    /**
583     * Tracks new system packages [received in an OTA] that we expect to
584     * find updated user-installed versions. Keys are package name, values
585     * are package location.
586     */
587    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
588    /**
589     * Tracks high priority intent filters for protected actions. During boot, certain
590     * filter actions are protected and should never be allowed to have a high priority
591     * intent filter for them. However, there is one, and only one exception -- the
592     * setup wizard. It must be able to define a high priority intent filter for these
593     * actions to ensure there are no escapes from the wizard. We need to delay processing
594     * of these during boot as we need to look at all of the system packages in order
595     * to know which component is the setup wizard.
596     */
597    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
598    /**
599     * Whether or not processing protected filters should be deferred.
600     */
601    private boolean mDeferProtectedFilters = true;
602
603    /**
604     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
605     */
606    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
607    /**
608     * Whether or not system app permissions should be promoted from install to runtime.
609     */
610    boolean mPromoteSystemApps;
611
612    @GuardedBy("mPackages")
613    final Settings mSettings;
614
615    /**
616     * Set of package names that are currently "frozen", which means active
617     * surgery is being done on the code/data for that package. The platform
618     * will refuse to launch frozen packages to avoid race conditions.
619     *
620     * @see PackageFreezer
621     */
622    @GuardedBy("mPackages")
623    final ArraySet<String> mFrozenPackages = new ArraySet<>();
624
625    final ProtectedPackages mProtectedPackages;
626
627    boolean mFirstBoot;
628
629    // System configuration read by SystemConfig.
630    final int[] mGlobalGids;
631    final SparseArray<ArraySet<String>> mSystemPermissions;
632    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
633
634    // If mac_permissions.xml was found for seinfo labeling.
635    boolean mFoundPolicyFile;
636
637    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
638
639    public static final class SharedLibraryEntry {
640        public final String path;
641        public final String apk;
642
643        SharedLibraryEntry(String _path, String _apk) {
644            path = _path;
645            apk = _apk;
646        }
647    }
648
649    // Currently known shared libraries.
650    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
651            new ArrayMap<String, SharedLibraryEntry>();
652
653    // All available activities, for your resolving pleasure.
654    final ActivityIntentResolver mActivities =
655            new ActivityIntentResolver();
656
657    // All available receivers, for your resolving pleasure.
658    final ActivityIntentResolver mReceivers =
659            new ActivityIntentResolver();
660
661    // All available services, for your resolving pleasure.
662    final ServiceIntentResolver mServices = new ServiceIntentResolver();
663
664    // All available providers, for your resolving pleasure.
665    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
666
667    // Mapping from provider base names (first directory in content URI codePath)
668    // to the provider information.
669    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
670            new ArrayMap<String, PackageParser.Provider>();
671
672    // Mapping from instrumentation class names to info about them.
673    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
674            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
675
676    // Mapping from permission names to info about them.
677    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
678            new ArrayMap<String, PackageParser.PermissionGroup>();
679
680    // Packages whose data we have transfered into another package, thus
681    // should no longer exist.
682    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
683
684    // Broadcast actions that are only available to the system.
685    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
686
687    /** List of packages waiting for verification. */
688    final SparseArray<PackageVerificationState> mPendingVerification
689            = new SparseArray<PackageVerificationState>();
690
691    /** Set of packages associated with each app op permission. */
692    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
693
694    final PackageInstallerService mInstallerService;
695
696    private final PackageDexOptimizer mPackageDexOptimizer;
697
698    private AtomicInteger mNextMoveId = new AtomicInteger();
699    private final MoveCallbacks mMoveCallbacks;
700
701    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
702
703    // Cache of users who need badging.
704    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
705
706    /** Token for keys in mPendingVerification. */
707    private int mPendingVerificationToken = 0;
708
709    volatile boolean mSystemReady;
710    volatile boolean mSafeMode;
711    volatile boolean mHasSystemUidErrors;
712
713    ApplicationInfo mAndroidApplication;
714    final ActivityInfo mResolveActivity = new ActivityInfo();
715    final ResolveInfo mResolveInfo = new ResolveInfo();
716    ComponentName mResolveComponentName;
717    PackageParser.Package mPlatformPackage;
718    ComponentName mCustomResolverComponentName;
719
720    boolean mResolverReplaced = false;
721
722    private final @Nullable ComponentName mIntentFilterVerifierComponent;
723    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
724
725    private int mIntentFilterVerificationToken = 0;
726
727    /** Component that knows whether or not an ephemeral application exists */
728    final ComponentName mEphemeralResolverComponent;
729    /** The service connection to the ephemeral resolver */
730    final EphemeralResolverConnection mEphemeralResolverConnection;
731
732    /** Component used to install ephemeral applications */
733    final ComponentName mEphemeralInstallerComponent;
734    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
735    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
736
737    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
738            = new SparseArray<IntentFilterVerificationState>();
739
740    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
741            new DefaultPermissionGrantPolicy(this);
742
743    // List of packages names to keep cached, even if they are uninstalled for all users
744    private List<String> mKeepUninstalledPackages;
745
746    private UserManagerInternal mUserManagerInternal;
747
748    private static class IFVerificationParams {
749        PackageParser.Package pkg;
750        boolean replacing;
751        int userId;
752        int verifierUid;
753
754        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
755                int _userId, int _verifierUid) {
756            pkg = _pkg;
757            replacing = _replacing;
758            userId = _userId;
759            replacing = _replacing;
760            verifierUid = _verifierUid;
761        }
762    }
763
764    private interface IntentFilterVerifier<T extends IntentFilter> {
765        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
766                                               T filter, String packageName);
767        void startVerifications(int userId);
768        void receiveVerificationResponse(int verificationId);
769    }
770
771    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
772        private Context mContext;
773        private ComponentName mIntentFilterVerifierComponent;
774        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
775
776        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
777            mContext = context;
778            mIntentFilterVerifierComponent = verifierComponent;
779        }
780
781        private String getDefaultScheme() {
782            return IntentFilter.SCHEME_HTTPS;
783        }
784
785        @Override
786        public void startVerifications(int userId) {
787            // Launch verifications requests
788            int count = mCurrentIntentFilterVerifications.size();
789            for (int n=0; n<count; n++) {
790                int verificationId = mCurrentIntentFilterVerifications.get(n);
791                final IntentFilterVerificationState ivs =
792                        mIntentFilterVerificationStates.get(verificationId);
793
794                String packageName = ivs.getPackageName();
795
796                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
797                final int filterCount = filters.size();
798                ArraySet<String> domainsSet = new ArraySet<>();
799                for (int m=0; m<filterCount; m++) {
800                    PackageParser.ActivityIntentInfo filter = filters.get(m);
801                    domainsSet.addAll(filter.getHostsList());
802                }
803                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
804                synchronized (mPackages) {
805                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
806                            packageName, domainsList) != null) {
807                        scheduleWriteSettingsLocked();
808                    }
809                }
810                sendVerificationRequest(userId, verificationId, ivs);
811            }
812            mCurrentIntentFilterVerifications.clear();
813        }
814
815        private void sendVerificationRequest(int userId, int verificationId,
816                IntentFilterVerificationState ivs) {
817
818            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
819            verificationIntent.putExtra(
820                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
821                    verificationId);
822            verificationIntent.putExtra(
823                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
824                    getDefaultScheme());
825            verificationIntent.putExtra(
826                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
827                    ivs.getHostsString());
828            verificationIntent.putExtra(
829                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
830                    ivs.getPackageName());
831            verificationIntent.setComponent(mIntentFilterVerifierComponent);
832            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
833
834            UserHandle user = new UserHandle(userId);
835            mContext.sendBroadcastAsUser(verificationIntent, user);
836            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
837                    "Sending IntentFilter verification broadcast");
838        }
839
840        public void receiveVerificationResponse(int verificationId) {
841            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
842
843            final boolean verified = ivs.isVerified();
844
845            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
846            final int count = filters.size();
847            if (DEBUG_DOMAIN_VERIFICATION) {
848                Slog.i(TAG, "Received verification response " + verificationId
849                        + " for " + count + " filters, verified=" + verified);
850            }
851            for (int n=0; n<count; n++) {
852                PackageParser.ActivityIntentInfo filter = filters.get(n);
853                filter.setVerified(verified);
854
855                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
856                        + " verified with result:" + verified + " and hosts:"
857                        + ivs.getHostsString());
858            }
859
860            mIntentFilterVerificationStates.remove(verificationId);
861
862            final String packageName = ivs.getPackageName();
863            IntentFilterVerificationInfo ivi = null;
864
865            synchronized (mPackages) {
866                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
867            }
868            if (ivi == null) {
869                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
870                        + verificationId + " packageName:" + packageName);
871                return;
872            }
873            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
874                    "Updating IntentFilterVerificationInfo for package " + packageName
875                            +" verificationId:" + verificationId);
876
877            synchronized (mPackages) {
878                if (verified) {
879                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
880                } else {
881                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
882                }
883                scheduleWriteSettingsLocked();
884
885                final int userId = ivs.getUserId();
886                if (userId != UserHandle.USER_ALL) {
887                    final int userStatus =
888                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
889
890                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
891                    boolean needUpdate = false;
892
893                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
894                    // already been set by the User thru the Disambiguation dialog
895                    switch (userStatus) {
896                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
897                            if (verified) {
898                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
899                            } else {
900                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
901                            }
902                            needUpdate = true;
903                            break;
904
905                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
906                            if (verified) {
907                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
908                                needUpdate = true;
909                            }
910                            break;
911
912                        default:
913                            // Nothing to do
914                    }
915
916                    if (needUpdate) {
917                        mSettings.updateIntentFilterVerificationStatusLPw(
918                                packageName, updatedStatus, userId);
919                        scheduleWritePackageRestrictionsLocked(userId);
920                    }
921                }
922            }
923        }
924
925        @Override
926        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
927                    ActivityIntentInfo filter, String packageName) {
928            if (!hasValidDomains(filter)) {
929                return false;
930            }
931            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
932            if (ivs == null) {
933                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
934                        packageName);
935            }
936            if (DEBUG_DOMAIN_VERIFICATION) {
937                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
938            }
939            ivs.addFilter(filter);
940            return true;
941        }
942
943        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
944                int userId, int verificationId, String packageName) {
945            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
946                    verifierUid, userId, packageName);
947            ivs.setPendingState();
948            synchronized (mPackages) {
949                mIntentFilterVerificationStates.append(verificationId, ivs);
950                mCurrentIntentFilterVerifications.add(verificationId);
951            }
952            return ivs;
953        }
954    }
955
956    private static boolean hasValidDomains(ActivityIntentInfo filter) {
957        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
958                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
959                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
960    }
961
962    // Set of pending broadcasts for aggregating enable/disable of components.
963    static class PendingPackageBroadcasts {
964        // for each user id, a map of <package name -> components within that package>
965        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
966
967        public PendingPackageBroadcasts() {
968            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
969        }
970
971        public ArrayList<String> get(int userId, String packageName) {
972            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
973            return packages.get(packageName);
974        }
975
976        public void put(int userId, String packageName, ArrayList<String> components) {
977            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
978            packages.put(packageName, components);
979        }
980
981        public void remove(int userId, String packageName) {
982            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
983            if (packages != null) {
984                packages.remove(packageName);
985            }
986        }
987
988        public void remove(int userId) {
989            mUidMap.remove(userId);
990        }
991
992        public int userIdCount() {
993            return mUidMap.size();
994        }
995
996        public int userIdAt(int n) {
997            return mUidMap.keyAt(n);
998        }
999
1000        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1001            return mUidMap.get(userId);
1002        }
1003
1004        public int size() {
1005            // total number of pending broadcast entries across all userIds
1006            int num = 0;
1007            for (int i = 0; i< mUidMap.size(); i++) {
1008                num += mUidMap.valueAt(i).size();
1009            }
1010            return num;
1011        }
1012
1013        public void clear() {
1014            mUidMap.clear();
1015        }
1016
1017        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1018            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1019            if (map == null) {
1020                map = new ArrayMap<String, ArrayList<String>>();
1021                mUidMap.put(userId, map);
1022            }
1023            return map;
1024        }
1025    }
1026    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1027
1028    // Service Connection to remote media container service to copy
1029    // package uri's from external media onto secure containers
1030    // or internal storage.
1031    private IMediaContainerService mContainerService = null;
1032
1033    static final int SEND_PENDING_BROADCAST = 1;
1034    static final int MCS_BOUND = 3;
1035    static final int END_COPY = 4;
1036    static final int INIT_COPY = 5;
1037    static final int MCS_UNBIND = 6;
1038    static final int START_CLEANING_PACKAGE = 7;
1039    static final int FIND_INSTALL_LOC = 8;
1040    static final int POST_INSTALL = 9;
1041    static final int MCS_RECONNECT = 10;
1042    static final int MCS_GIVE_UP = 11;
1043    static final int UPDATED_MEDIA_STATUS = 12;
1044    static final int WRITE_SETTINGS = 13;
1045    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1046    static final int PACKAGE_VERIFIED = 15;
1047    static final int CHECK_PENDING_VERIFICATION = 16;
1048    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1049    static final int INTENT_FILTER_VERIFIED = 18;
1050    static final int WRITE_PACKAGE_LIST = 19;
1051
1052    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1053
1054    // Delay time in millisecs
1055    static final int BROADCAST_DELAY = 10 * 1000;
1056
1057    static UserManagerService sUserManager;
1058
1059    // Stores a list of users whose package restrictions file needs to be updated
1060    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1061
1062    final private DefaultContainerConnection mDefContainerConn =
1063            new DefaultContainerConnection();
1064    class DefaultContainerConnection implements ServiceConnection {
1065        public void onServiceConnected(ComponentName name, IBinder service) {
1066            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1067            IMediaContainerService imcs =
1068                IMediaContainerService.Stub.asInterface(service);
1069            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1070        }
1071
1072        public void onServiceDisconnected(ComponentName name) {
1073            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1074        }
1075    }
1076
1077    // Recordkeeping of restore-after-install operations that are currently in flight
1078    // between the Package Manager and the Backup Manager
1079    static class PostInstallData {
1080        public InstallArgs args;
1081        public PackageInstalledInfo res;
1082
1083        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1084            args = _a;
1085            res = _r;
1086        }
1087    }
1088
1089    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1090    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1091
1092    // XML tags for backup/restore of various bits of state
1093    private static final String TAG_PREFERRED_BACKUP = "pa";
1094    private static final String TAG_DEFAULT_APPS = "da";
1095    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1096
1097    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1098    private static final String TAG_ALL_GRANTS = "rt-grants";
1099    private static final String TAG_GRANT = "grant";
1100    private static final String ATTR_PACKAGE_NAME = "pkg";
1101
1102    private static final String TAG_PERMISSION = "perm";
1103    private static final String ATTR_PERMISSION_NAME = "name";
1104    private static final String ATTR_IS_GRANTED = "g";
1105    private static final String ATTR_USER_SET = "set";
1106    private static final String ATTR_USER_FIXED = "fixed";
1107    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1108
1109    // System/policy permission grants are not backed up
1110    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1111            FLAG_PERMISSION_POLICY_FIXED
1112            | FLAG_PERMISSION_SYSTEM_FIXED
1113            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1114
1115    // And we back up these user-adjusted states
1116    private static final int USER_RUNTIME_GRANT_MASK =
1117            FLAG_PERMISSION_USER_SET
1118            | FLAG_PERMISSION_USER_FIXED
1119            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1120
1121    final @Nullable String mRequiredVerifierPackage;
1122    final @NonNull String mRequiredInstallerPackage;
1123    final @Nullable String mSetupWizardPackage;
1124    final @NonNull String mServicesSystemSharedLibraryPackageName;
1125    final @NonNull String mSharedSystemSharedLibraryPackageName;
1126
1127    private final PackageUsage mPackageUsage = new PackageUsage();
1128    private final CompilerStats mCompilerStats = new CompilerStats();
1129
1130    class PackageHandler extends Handler {
1131        private boolean mBound = false;
1132        final ArrayList<HandlerParams> mPendingInstalls =
1133            new ArrayList<HandlerParams>();
1134
1135        private boolean connectToService() {
1136            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1137                    " DefaultContainerService");
1138            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1139            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1140            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1141                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1142                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1143                mBound = true;
1144                return true;
1145            }
1146            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1147            return false;
1148        }
1149
1150        private void disconnectService() {
1151            mContainerService = null;
1152            mBound = false;
1153            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1154            mContext.unbindService(mDefContainerConn);
1155            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1156        }
1157
1158        PackageHandler(Looper looper) {
1159            super(looper);
1160        }
1161
1162        public void handleMessage(Message msg) {
1163            try {
1164                doHandleMessage(msg);
1165            } finally {
1166                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1167            }
1168        }
1169
1170        void doHandleMessage(Message msg) {
1171            switch (msg.what) {
1172                case INIT_COPY: {
1173                    HandlerParams params = (HandlerParams) msg.obj;
1174                    int idx = mPendingInstalls.size();
1175                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1176                    // If a bind was already initiated we dont really
1177                    // need to do anything. The pending install
1178                    // will be processed later on.
1179                    if (!mBound) {
1180                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1181                                System.identityHashCode(mHandler));
1182                        // If this is the only one pending we might
1183                        // have to bind to the service again.
1184                        if (!connectToService()) {
1185                            Slog.e(TAG, "Failed to bind to media container service");
1186                            params.serviceError();
1187                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1188                                    System.identityHashCode(mHandler));
1189                            if (params.traceMethod != null) {
1190                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1191                                        params.traceCookie);
1192                            }
1193                            return;
1194                        } else {
1195                            // Once we bind to the service, the first
1196                            // pending request will be processed.
1197                            mPendingInstalls.add(idx, params);
1198                        }
1199                    } else {
1200                        mPendingInstalls.add(idx, params);
1201                        // Already bound to the service. Just make
1202                        // sure we trigger off processing the first request.
1203                        if (idx == 0) {
1204                            mHandler.sendEmptyMessage(MCS_BOUND);
1205                        }
1206                    }
1207                    break;
1208                }
1209                case MCS_BOUND: {
1210                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1211                    if (msg.obj != null) {
1212                        mContainerService = (IMediaContainerService) msg.obj;
1213                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1214                                System.identityHashCode(mHandler));
1215                    }
1216                    if (mContainerService == null) {
1217                        if (!mBound) {
1218                            // Something seriously wrong since we are not bound and we are not
1219                            // waiting for connection. Bail out.
1220                            Slog.e(TAG, "Cannot bind to media container service");
1221                            for (HandlerParams params : mPendingInstalls) {
1222                                // Indicate service bind error
1223                                params.serviceError();
1224                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1225                                        System.identityHashCode(params));
1226                                if (params.traceMethod != null) {
1227                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1228                                            params.traceMethod, params.traceCookie);
1229                                }
1230                                return;
1231                            }
1232                            mPendingInstalls.clear();
1233                        } else {
1234                            Slog.w(TAG, "Waiting to connect to media container service");
1235                        }
1236                    } else if (mPendingInstalls.size() > 0) {
1237                        HandlerParams params = mPendingInstalls.get(0);
1238                        if (params != null) {
1239                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1240                                    System.identityHashCode(params));
1241                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1242                            if (params.startCopy()) {
1243                                // We are done...  look for more work or to
1244                                // go idle.
1245                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1246                                        "Checking for more work or unbind...");
1247                                // Delete pending install
1248                                if (mPendingInstalls.size() > 0) {
1249                                    mPendingInstalls.remove(0);
1250                                }
1251                                if (mPendingInstalls.size() == 0) {
1252                                    if (mBound) {
1253                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1254                                                "Posting delayed MCS_UNBIND");
1255                                        removeMessages(MCS_UNBIND);
1256                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1257                                        // Unbind after a little delay, to avoid
1258                                        // continual thrashing.
1259                                        sendMessageDelayed(ubmsg, 10000);
1260                                    }
1261                                } else {
1262                                    // There are more pending requests in queue.
1263                                    // Just post MCS_BOUND message to trigger processing
1264                                    // of next pending install.
1265                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1266                                            "Posting MCS_BOUND for next work");
1267                                    mHandler.sendEmptyMessage(MCS_BOUND);
1268                                }
1269                            }
1270                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1271                        }
1272                    } else {
1273                        // Should never happen ideally.
1274                        Slog.w(TAG, "Empty queue");
1275                    }
1276                    break;
1277                }
1278                case MCS_RECONNECT: {
1279                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1280                    if (mPendingInstalls.size() > 0) {
1281                        if (mBound) {
1282                            disconnectService();
1283                        }
1284                        if (!connectToService()) {
1285                            Slog.e(TAG, "Failed to bind to media container service");
1286                            for (HandlerParams params : mPendingInstalls) {
1287                                // Indicate service bind error
1288                                params.serviceError();
1289                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1290                                        System.identityHashCode(params));
1291                            }
1292                            mPendingInstalls.clear();
1293                        }
1294                    }
1295                    break;
1296                }
1297                case MCS_UNBIND: {
1298                    // If there is no actual work left, then time to unbind.
1299                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1300
1301                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1302                        if (mBound) {
1303                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1304
1305                            disconnectService();
1306                        }
1307                    } else if (mPendingInstalls.size() > 0) {
1308                        // There are more pending requests in queue.
1309                        // Just post MCS_BOUND message to trigger processing
1310                        // of next pending install.
1311                        mHandler.sendEmptyMessage(MCS_BOUND);
1312                    }
1313
1314                    break;
1315                }
1316                case MCS_GIVE_UP: {
1317                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1318                    HandlerParams params = mPendingInstalls.remove(0);
1319                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1320                            System.identityHashCode(params));
1321                    break;
1322                }
1323                case SEND_PENDING_BROADCAST: {
1324                    String packages[];
1325                    ArrayList<String> components[];
1326                    int size = 0;
1327                    int uids[];
1328                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1329                    synchronized (mPackages) {
1330                        if (mPendingBroadcasts == null) {
1331                            return;
1332                        }
1333                        size = mPendingBroadcasts.size();
1334                        if (size <= 0) {
1335                            // Nothing to be done. Just return
1336                            return;
1337                        }
1338                        packages = new String[size];
1339                        components = new ArrayList[size];
1340                        uids = new int[size];
1341                        int i = 0;  // filling out the above arrays
1342
1343                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1344                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1345                            Iterator<Map.Entry<String, ArrayList<String>>> it
1346                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1347                                            .entrySet().iterator();
1348                            while (it.hasNext() && i < size) {
1349                                Map.Entry<String, ArrayList<String>> ent = it.next();
1350                                packages[i] = ent.getKey();
1351                                components[i] = ent.getValue();
1352                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1353                                uids[i] = (ps != null)
1354                                        ? UserHandle.getUid(packageUserId, ps.appId)
1355                                        : -1;
1356                                i++;
1357                            }
1358                        }
1359                        size = i;
1360                        mPendingBroadcasts.clear();
1361                    }
1362                    // Send broadcasts
1363                    for (int i = 0; i < size; i++) {
1364                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1365                    }
1366                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1367                    break;
1368                }
1369                case START_CLEANING_PACKAGE: {
1370                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1371                    final String packageName = (String)msg.obj;
1372                    final int userId = msg.arg1;
1373                    final boolean andCode = msg.arg2 != 0;
1374                    synchronized (mPackages) {
1375                        if (userId == UserHandle.USER_ALL) {
1376                            int[] users = sUserManager.getUserIds();
1377                            for (int user : users) {
1378                                mSettings.addPackageToCleanLPw(
1379                                        new PackageCleanItem(user, packageName, andCode));
1380                            }
1381                        } else {
1382                            mSettings.addPackageToCleanLPw(
1383                                    new PackageCleanItem(userId, packageName, andCode));
1384                        }
1385                    }
1386                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1387                    startCleaningPackages();
1388                } break;
1389                case POST_INSTALL: {
1390                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1391
1392                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1393                    final boolean didRestore = (msg.arg2 != 0);
1394                    mRunningInstalls.delete(msg.arg1);
1395
1396                    if (data != null) {
1397                        InstallArgs args = data.args;
1398                        PackageInstalledInfo parentRes = data.res;
1399
1400                        final boolean grantPermissions = (args.installFlags
1401                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1402                        final boolean killApp = (args.installFlags
1403                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1404                        final String[] grantedPermissions = args.installGrantPermissions;
1405
1406                        // Handle the parent package
1407                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1408                                grantedPermissions, didRestore, args.installerPackageName,
1409                                args.observer);
1410
1411                        // Handle the child packages
1412                        final int childCount = (parentRes.addedChildPackages != null)
1413                                ? parentRes.addedChildPackages.size() : 0;
1414                        for (int i = 0; i < childCount; i++) {
1415                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1416                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1417                                    grantedPermissions, false, args.installerPackageName,
1418                                    args.observer);
1419                        }
1420
1421                        // Log tracing if needed
1422                        if (args.traceMethod != null) {
1423                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1424                                    args.traceCookie);
1425                        }
1426                    } else {
1427                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1428                    }
1429
1430                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1431                } break;
1432                case UPDATED_MEDIA_STATUS: {
1433                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1434                    boolean reportStatus = msg.arg1 == 1;
1435                    boolean doGc = msg.arg2 == 1;
1436                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1437                    if (doGc) {
1438                        // Force a gc to clear up stale containers.
1439                        Runtime.getRuntime().gc();
1440                    }
1441                    if (msg.obj != null) {
1442                        @SuppressWarnings("unchecked")
1443                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1444                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1445                        // Unload containers
1446                        unloadAllContainers(args);
1447                    }
1448                    if (reportStatus) {
1449                        try {
1450                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1451                            PackageHelper.getMountService().finishMediaUpdate();
1452                        } catch (RemoteException e) {
1453                            Log.e(TAG, "MountService not running?");
1454                        }
1455                    }
1456                } break;
1457                case WRITE_SETTINGS: {
1458                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1459                    synchronized (mPackages) {
1460                        removeMessages(WRITE_SETTINGS);
1461                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1462                        mSettings.writeLPr();
1463                        mDirtyUsers.clear();
1464                    }
1465                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1466                } break;
1467                case WRITE_PACKAGE_RESTRICTIONS: {
1468                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1469                    synchronized (mPackages) {
1470                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1471                        for (int userId : mDirtyUsers) {
1472                            mSettings.writePackageRestrictionsLPr(userId);
1473                        }
1474                        mDirtyUsers.clear();
1475                    }
1476                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1477                } break;
1478                case WRITE_PACKAGE_LIST: {
1479                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1480                    synchronized (mPackages) {
1481                        removeMessages(WRITE_PACKAGE_LIST);
1482                        mSettings.writePackageListLPr(msg.arg1);
1483                    }
1484                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1485                } break;
1486                case CHECK_PENDING_VERIFICATION: {
1487                    final int verificationId = msg.arg1;
1488                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1489
1490                    if ((state != null) && !state.timeoutExtended()) {
1491                        final InstallArgs args = state.getInstallArgs();
1492                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1493
1494                        Slog.i(TAG, "Verification timed out for " + originUri);
1495                        mPendingVerification.remove(verificationId);
1496
1497                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1498
1499                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1500                            Slog.i(TAG, "Continuing with installation of " + originUri);
1501                            state.setVerifierResponse(Binder.getCallingUid(),
1502                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1503                            broadcastPackageVerified(verificationId, originUri,
1504                                    PackageManager.VERIFICATION_ALLOW,
1505                                    state.getInstallArgs().getUser());
1506                            try {
1507                                ret = args.copyApk(mContainerService, true);
1508                            } catch (RemoteException e) {
1509                                Slog.e(TAG, "Could not contact the ContainerService");
1510                            }
1511                        } else {
1512                            broadcastPackageVerified(verificationId, originUri,
1513                                    PackageManager.VERIFICATION_REJECT,
1514                                    state.getInstallArgs().getUser());
1515                        }
1516
1517                        Trace.asyncTraceEnd(
1518                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1519
1520                        processPendingInstall(args, ret);
1521                        mHandler.sendEmptyMessage(MCS_UNBIND);
1522                    }
1523                    break;
1524                }
1525                case PACKAGE_VERIFIED: {
1526                    final int verificationId = msg.arg1;
1527
1528                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1529                    if (state == null) {
1530                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1531                        break;
1532                    }
1533
1534                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1535
1536                    state.setVerifierResponse(response.callerUid, response.code);
1537
1538                    if (state.isVerificationComplete()) {
1539                        mPendingVerification.remove(verificationId);
1540
1541                        final InstallArgs args = state.getInstallArgs();
1542                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1543
1544                        int ret;
1545                        if (state.isInstallAllowed()) {
1546                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1547                            broadcastPackageVerified(verificationId, originUri,
1548                                    response.code, state.getInstallArgs().getUser());
1549                            try {
1550                                ret = args.copyApk(mContainerService, true);
1551                            } catch (RemoteException e) {
1552                                Slog.e(TAG, "Could not contact the ContainerService");
1553                            }
1554                        } else {
1555                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1556                        }
1557
1558                        Trace.asyncTraceEnd(
1559                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1560
1561                        processPendingInstall(args, ret);
1562                        mHandler.sendEmptyMessage(MCS_UNBIND);
1563                    }
1564
1565                    break;
1566                }
1567                case START_INTENT_FILTER_VERIFICATIONS: {
1568                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1569                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1570                            params.replacing, params.pkg);
1571                    break;
1572                }
1573                case INTENT_FILTER_VERIFIED: {
1574                    final int verificationId = msg.arg1;
1575
1576                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1577                            verificationId);
1578                    if (state == null) {
1579                        Slog.w(TAG, "Invalid IntentFilter verification token "
1580                                + verificationId + " received");
1581                        break;
1582                    }
1583
1584                    final int userId = state.getUserId();
1585
1586                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1587                            "Processing IntentFilter verification with token:"
1588                            + verificationId + " and userId:" + userId);
1589
1590                    final IntentFilterVerificationResponse response =
1591                            (IntentFilterVerificationResponse) msg.obj;
1592
1593                    state.setVerifierResponse(response.callerUid, response.code);
1594
1595                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1596                            "IntentFilter verification with token:" + verificationId
1597                            + " and userId:" + userId
1598                            + " is settings verifier response with response code:"
1599                            + response.code);
1600
1601                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1602                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1603                                + response.getFailedDomainsString());
1604                    }
1605
1606                    if (state.isVerificationComplete()) {
1607                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1608                    } else {
1609                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1610                                "IntentFilter verification with token:" + verificationId
1611                                + " was not said to be complete");
1612                    }
1613
1614                    break;
1615                }
1616            }
1617        }
1618    }
1619
1620    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1621            boolean killApp, String[] grantedPermissions,
1622            boolean launchedForRestore, String installerPackage,
1623            IPackageInstallObserver2 installObserver) {
1624        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1625            // Send the removed broadcasts
1626            if (res.removedInfo != null) {
1627                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1628            }
1629
1630            // Now that we successfully installed the package, grant runtime
1631            // permissions if requested before broadcasting the install.
1632            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1633                    >= Build.VERSION_CODES.M) {
1634                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1635            }
1636
1637            final boolean update = res.removedInfo != null
1638                    && res.removedInfo.removedPackage != null;
1639
1640            // If this is the first time we have child packages for a disabled privileged
1641            // app that had no children, we grant requested runtime permissions to the new
1642            // children if the parent on the system image had them already granted.
1643            if (res.pkg.parentPackage != null) {
1644                synchronized (mPackages) {
1645                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1646                }
1647            }
1648
1649            synchronized (mPackages) {
1650                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1651            }
1652
1653            final String packageName = res.pkg.applicationInfo.packageName;
1654            Bundle extras = new Bundle(1);
1655            extras.putInt(Intent.EXTRA_UID, res.uid);
1656
1657            // Determine the set of users who are adding this package for
1658            // the first time vs. those who are seeing an update.
1659            int[] firstUsers = EMPTY_INT_ARRAY;
1660            int[] updateUsers = EMPTY_INT_ARRAY;
1661            if (res.origUsers == null || res.origUsers.length == 0) {
1662                firstUsers = res.newUsers;
1663            } else {
1664                for (int newUser : res.newUsers) {
1665                    boolean isNew = true;
1666                    for (int origUser : res.origUsers) {
1667                        if (origUser == newUser) {
1668                            isNew = false;
1669                            break;
1670                        }
1671                    }
1672                    if (isNew) {
1673                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1674                    } else {
1675                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1676                    }
1677                }
1678            }
1679
1680            // Send installed broadcasts if the install/update is not ephemeral
1681            if (!isEphemeral(res.pkg)) {
1682                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1683
1684                // Send added for users that see the package for the first time
1685                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1686                        extras, 0 /*flags*/, null /*targetPackage*/,
1687                        null /*finishedReceiver*/, firstUsers);
1688
1689                // Send added for users that don't see the package for the first time
1690                if (update) {
1691                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1692                }
1693                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1694                        extras, 0 /*flags*/, null /*targetPackage*/,
1695                        null /*finishedReceiver*/, updateUsers);
1696
1697                // Send replaced for users that don't see the package for the first time
1698                if (update) {
1699                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1700                            packageName, extras, 0 /*flags*/,
1701                            null /*targetPackage*/, null /*finishedReceiver*/,
1702                            updateUsers);
1703                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1704                            null /*package*/, null /*extras*/, 0 /*flags*/,
1705                            packageName /*targetPackage*/,
1706                            null /*finishedReceiver*/, updateUsers);
1707                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1708                    // First-install and we did a restore, so we're responsible for the
1709                    // first-launch broadcast.
1710                    if (DEBUG_BACKUP) {
1711                        Slog.i(TAG, "Post-restore of " + packageName
1712                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1713                    }
1714                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1715                }
1716
1717                // Send broadcast package appeared if forward locked/external for all users
1718                // treat asec-hosted packages like removable media on upgrade
1719                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1720                    if (DEBUG_INSTALL) {
1721                        Slog.i(TAG, "upgrading pkg " + res.pkg
1722                                + " is ASEC-hosted -> AVAILABLE");
1723                    }
1724                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1725                    ArrayList<String> pkgList = new ArrayList<>(1);
1726                    pkgList.add(packageName);
1727                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1728                }
1729            }
1730
1731            // Work that needs to happen on first install within each user
1732            if (firstUsers != null && firstUsers.length > 0) {
1733                synchronized (mPackages) {
1734                    for (int userId : firstUsers) {
1735                        // If this app is a browser and it's newly-installed for some
1736                        // users, clear any default-browser state in those users. The
1737                        // app's nature doesn't depend on the user, so we can just check
1738                        // its browser nature in any user and generalize.
1739                        if (packageIsBrowser(packageName, userId)) {
1740                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1741                        }
1742
1743                        // We may also need to apply pending (restored) runtime
1744                        // permission grants within these users.
1745                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1746                    }
1747                }
1748            }
1749
1750            // Log current value of "unknown sources" setting
1751            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1752                    getUnknownSourcesSettings());
1753
1754            // Force a gc to clear up things
1755            Runtime.getRuntime().gc();
1756
1757            // Remove the replaced package's older resources safely now
1758            // We delete after a gc for applications  on sdcard.
1759            if (res.removedInfo != null && res.removedInfo.args != null) {
1760                synchronized (mInstallLock) {
1761                    res.removedInfo.args.doPostDeleteLI(true);
1762                }
1763            }
1764        }
1765
1766        // If someone is watching installs - notify them
1767        if (installObserver != null) {
1768            try {
1769                Bundle extras = extrasForInstallResult(res);
1770                installObserver.onPackageInstalled(res.name, res.returnCode,
1771                        res.returnMsg, extras);
1772            } catch (RemoteException e) {
1773                Slog.i(TAG, "Observer no longer exists.");
1774            }
1775        }
1776    }
1777
1778    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1779            PackageParser.Package pkg) {
1780        if (pkg.parentPackage == null) {
1781            return;
1782        }
1783        if (pkg.requestedPermissions == null) {
1784            return;
1785        }
1786        final PackageSetting disabledSysParentPs = mSettings
1787                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1788        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1789                || !disabledSysParentPs.isPrivileged()
1790                || (disabledSysParentPs.childPackageNames != null
1791                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1792            return;
1793        }
1794        final int[] allUserIds = sUserManager.getUserIds();
1795        final int permCount = pkg.requestedPermissions.size();
1796        for (int i = 0; i < permCount; i++) {
1797            String permission = pkg.requestedPermissions.get(i);
1798            BasePermission bp = mSettings.mPermissions.get(permission);
1799            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1800                continue;
1801            }
1802            for (int userId : allUserIds) {
1803                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1804                        permission, userId)) {
1805                    grantRuntimePermission(pkg.packageName, permission, userId);
1806                }
1807            }
1808        }
1809    }
1810
1811    private StorageEventListener mStorageListener = new StorageEventListener() {
1812        @Override
1813        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1814            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1815                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1816                    final String volumeUuid = vol.getFsUuid();
1817
1818                    // Clean up any users or apps that were removed or recreated
1819                    // while this volume was missing
1820                    reconcileUsers(volumeUuid);
1821                    reconcileApps(volumeUuid);
1822
1823                    // Clean up any install sessions that expired or were
1824                    // cancelled while this volume was missing
1825                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1826
1827                    loadPrivatePackages(vol);
1828
1829                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1830                    unloadPrivatePackages(vol);
1831                }
1832            }
1833
1834            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1835                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1836                    updateExternalMediaStatus(true, false);
1837                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1838                    updateExternalMediaStatus(false, false);
1839                }
1840            }
1841        }
1842
1843        @Override
1844        public void onVolumeForgotten(String fsUuid) {
1845            if (TextUtils.isEmpty(fsUuid)) {
1846                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1847                return;
1848            }
1849
1850            // Remove any apps installed on the forgotten volume
1851            synchronized (mPackages) {
1852                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1853                for (PackageSetting ps : packages) {
1854                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1855                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1856                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1857                }
1858
1859                mSettings.onVolumeForgotten(fsUuid);
1860                mSettings.writeLPr();
1861            }
1862        }
1863    };
1864
1865    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1866            String[] grantedPermissions) {
1867        for (int userId : userIds) {
1868            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1869        }
1870
1871        // We could have touched GID membership, so flush out packages.list
1872        synchronized (mPackages) {
1873            mSettings.writePackageListLPr();
1874        }
1875    }
1876
1877    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1878            String[] grantedPermissions) {
1879        SettingBase sb = (SettingBase) pkg.mExtras;
1880        if (sb == null) {
1881            return;
1882        }
1883
1884        PermissionsState permissionsState = sb.getPermissionsState();
1885
1886        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1887                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1888
1889        for (String permission : pkg.requestedPermissions) {
1890            final BasePermission bp;
1891            synchronized (mPackages) {
1892                bp = mSettings.mPermissions.get(permission);
1893            }
1894            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1895                    && (grantedPermissions == null
1896                           || ArrayUtils.contains(grantedPermissions, permission))) {
1897                final int flags = permissionsState.getPermissionFlags(permission, userId);
1898                // Installer cannot change immutable permissions.
1899                if ((flags & immutableFlags) == 0) {
1900                    grantRuntimePermission(pkg.packageName, permission, userId);
1901                }
1902            }
1903        }
1904    }
1905
1906    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1907        Bundle extras = null;
1908        switch (res.returnCode) {
1909            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1910                extras = new Bundle();
1911                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1912                        res.origPermission);
1913                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1914                        res.origPackage);
1915                break;
1916            }
1917            case PackageManager.INSTALL_SUCCEEDED: {
1918                extras = new Bundle();
1919                extras.putBoolean(Intent.EXTRA_REPLACING,
1920                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1921                break;
1922            }
1923        }
1924        return extras;
1925    }
1926
1927    void scheduleWriteSettingsLocked() {
1928        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1929            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1930        }
1931    }
1932
1933    void scheduleWritePackageListLocked(int userId) {
1934        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1935            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1936            msg.arg1 = userId;
1937            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1938        }
1939    }
1940
1941    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1942        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1943        scheduleWritePackageRestrictionsLocked(userId);
1944    }
1945
1946    void scheduleWritePackageRestrictionsLocked(int userId) {
1947        final int[] userIds = (userId == UserHandle.USER_ALL)
1948                ? sUserManager.getUserIds() : new int[]{userId};
1949        for (int nextUserId : userIds) {
1950            if (!sUserManager.exists(nextUserId)) return;
1951            mDirtyUsers.add(nextUserId);
1952            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1953                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1954            }
1955        }
1956    }
1957
1958    public static PackageManagerService main(Context context, Installer installer,
1959            boolean factoryTest, boolean onlyCore) {
1960        // Self-check for initial settings.
1961        PackageManagerServiceCompilerMapping.checkProperties();
1962
1963        PackageManagerService m = new PackageManagerService(context, installer,
1964                factoryTest, onlyCore);
1965        m.enableSystemUserPackages();
1966        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
1967        // disabled after already being started.
1968        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
1969                UserHandle.USER_SYSTEM);
1970        ServiceManager.addService("package", m);
1971        return m;
1972    }
1973
1974    private void enableSystemUserPackages() {
1975        if (!UserManager.isSplitSystemUser()) {
1976            return;
1977        }
1978        // For system user, enable apps based on the following conditions:
1979        // - app is whitelisted or belong to one of these groups:
1980        //   -- system app which has no launcher icons
1981        //   -- system app which has INTERACT_ACROSS_USERS permission
1982        //   -- system IME app
1983        // - app is not in the blacklist
1984        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1985        Set<String> enableApps = new ArraySet<>();
1986        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1987                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1988                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1989        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1990        enableApps.addAll(wlApps);
1991        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1992                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1993        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1994        enableApps.removeAll(blApps);
1995        Log.i(TAG, "Applications installed for system user: " + enableApps);
1996        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1997                UserHandle.SYSTEM);
1998        final int allAppsSize = allAps.size();
1999        synchronized (mPackages) {
2000            for (int i = 0; i < allAppsSize; i++) {
2001                String pName = allAps.get(i);
2002                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2003                // Should not happen, but we shouldn't be failing if it does
2004                if (pkgSetting == null) {
2005                    continue;
2006                }
2007                boolean install = enableApps.contains(pName);
2008                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2009                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2010                            + " for system user");
2011                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2012                }
2013            }
2014        }
2015    }
2016
2017    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2018        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2019                Context.DISPLAY_SERVICE);
2020        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2021    }
2022
2023    /**
2024     * Requests that files preopted on a secondary system partition be copied to the data partition
2025     * if possible.  Note that the actual copying of the files is accomplished by init for security
2026     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2027     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2028     */
2029    private static void requestCopyPreoptedFiles() {
2030        final int WAIT_TIME_MS = 100;
2031        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2032        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2033            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2034            // We will wait for up to 100 seconds.
2035            final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000;
2036            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2037                try {
2038                    Thread.sleep(WAIT_TIME_MS);
2039                } catch (InterruptedException e) {
2040                    // Do nothing
2041                }
2042                if (SystemClock.uptimeMillis() > timeEnd) {
2043                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2044                    Slog.wtf(TAG, "cppreopt did not finish!");
2045                    break;
2046                }
2047            }
2048        }
2049    }
2050
2051    public PackageManagerService(Context context, Installer installer,
2052            boolean factoryTest, boolean onlyCore) {
2053        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2054        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2055                SystemClock.uptimeMillis());
2056
2057        if (mSdkVersion <= 0) {
2058            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2059        }
2060
2061        mContext = context;
2062        mFactoryTest = factoryTest;
2063        mOnlyCore = onlyCore;
2064        mMetrics = new DisplayMetrics();
2065        mSettings = new Settings(mPackages);
2066        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2067                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2068        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2069                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2070        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2071                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2072        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2073                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2074        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2075                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2076        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2077                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2078
2079        String separateProcesses = SystemProperties.get("debug.separate_processes");
2080        if (separateProcesses != null && separateProcesses.length() > 0) {
2081            if ("*".equals(separateProcesses)) {
2082                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2083                mSeparateProcesses = null;
2084                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2085            } else {
2086                mDefParseFlags = 0;
2087                mSeparateProcesses = separateProcesses.split(",");
2088                Slog.w(TAG, "Running with debug.separate_processes: "
2089                        + separateProcesses);
2090            }
2091        } else {
2092            mDefParseFlags = 0;
2093            mSeparateProcesses = null;
2094        }
2095
2096        mInstaller = installer;
2097        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2098                "*dexopt*");
2099        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2100
2101        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2102                FgThread.get().getLooper());
2103
2104        getDefaultDisplayMetrics(context, mMetrics);
2105
2106        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2107        SystemConfig systemConfig = SystemConfig.getInstance();
2108        mGlobalGids = systemConfig.getGlobalGids();
2109        mSystemPermissions = systemConfig.getSystemPermissions();
2110        mAvailableFeatures = systemConfig.getAvailableFeatures();
2111        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2112
2113        mProtectedPackages = new ProtectedPackages(mContext);
2114
2115        synchronized (mInstallLock) {
2116        // writer
2117        synchronized (mPackages) {
2118            mHandlerThread = new ServiceThread(TAG,
2119                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2120            mHandlerThread.start();
2121            mHandler = new PackageHandler(mHandlerThread.getLooper());
2122            mProcessLoggingHandler = new ProcessLoggingHandler();
2123            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2124
2125            File dataDir = Environment.getDataDirectory();
2126            mAppInstallDir = new File(dataDir, "app");
2127            mAppLib32InstallDir = new File(dataDir, "app-lib");
2128            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2129            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2130            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2131
2132            sUserManager = new UserManagerService(context, this, mPackages);
2133
2134            // Propagate permission configuration in to package manager.
2135            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2136                    = systemConfig.getPermissions();
2137            for (int i=0; i<permConfig.size(); i++) {
2138                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2139                BasePermission bp = mSettings.mPermissions.get(perm.name);
2140                if (bp == null) {
2141                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2142                    mSettings.mPermissions.put(perm.name, bp);
2143                }
2144                if (perm.gids != null) {
2145                    bp.setGids(perm.gids, perm.perUser);
2146                }
2147            }
2148
2149            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2150            for (int i=0; i<libConfig.size(); i++) {
2151                mSharedLibraries.put(libConfig.keyAt(i),
2152                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2153            }
2154
2155            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2156
2157            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2158            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2159            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2160
2161            if (mFirstBoot) {
2162                requestCopyPreoptedFiles();
2163            }
2164
2165            String customResolverActivity = Resources.getSystem().getString(
2166                    R.string.config_customResolverActivity);
2167            if (TextUtils.isEmpty(customResolverActivity)) {
2168                customResolverActivity = null;
2169            } else {
2170                mCustomResolverComponentName = ComponentName.unflattenFromString(
2171                        customResolverActivity);
2172            }
2173
2174            long startTime = SystemClock.uptimeMillis();
2175
2176            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2177                    startTime);
2178
2179            // Set flag to monitor and not change apk file paths when
2180            // scanning install directories.
2181            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2182
2183            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2184            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2185
2186            if (bootClassPath == null) {
2187                Slog.w(TAG, "No BOOTCLASSPATH found!");
2188            }
2189
2190            if (systemServerClassPath == null) {
2191                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2192            }
2193
2194            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2195            final String[] dexCodeInstructionSets =
2196                    getDexCodeInstructionSets(
2197                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2198
2199            /**
2200             * Ensure all external libraries have had dexopt run on them.
2201             */
2202            if (mSharedLibraries.size() > 0) {
2203                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
2204                // NOTE: For now, we're compiling these system "shared libraries"
2205                // (and framework jars) into all available architectures. It's possible
2206                // to compile them only when we come across an app that uses them (there's
2207                // already logic for that in scanPackageLI) but that adds some complexity.
2208                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2209                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2210                        final String lib = libEntry.path;
2211                        if (lib == null) {
2212                            continue;
2213                        }
2214
2215                        try {
2216                            // Shared libraries do not have profiles so we perform a full
2217                            // AOT compilation (if needed).
2218                            int dexoptNeeded = DexFile.getDexOptNeeded(
2219                                    lib, dexCodeInstructionSet,
2220                                    getCompilerFilterForReason(REASON_SHARED_APK),
2221                                    false /* newProfile */);
2222                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2223                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2224                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2225                                        getCompilerFilterForReason(REASON_SHARED_APK),
2226                                        StorageManager.UUID_PRIVATE_INTERNAL,
2227                                        SKIP_SHARED_LIBRARY_CHECK);
2228                            }
2229                        } catch (FileNotFoundException e) {
2230                            Slog.w(TAG, "Library not found: " + lib);
2231                        } catch (IOException | InstallerException e) {
2232                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2233                                    + e.getMessage());
2234                        }
2235                    }
2236                }
2237                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2238            }
2239
2240            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2241
2242            final VersionInfo ver = mSettings.getInternalVersion();
2243            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2244
2245            // when upgrading from pre-M, promote system app permissions from install to runtime
2246            mPromoteSystemApps =
2247                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2248
2249            // When upgrading from pre-N, we need to handle package extraction like first boot,
2250            // as there is no profiling data available.
2251            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2252
2253            // save off the names of pre-existing system packages prior to scanning; we don't
2254            // want to automatically grant runtime permissions for new system apps
2255            if (mPromoteSystemApps) {
2256                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2257                while (pkgSettingIter.hasNext()) {
2258                    PackageSetting ps = pkgSettingIter.next();
2259                    if (isSystemApp(ps)) {
2260                        mExistingSystemPackages.add(ps.name);
2261                    }
2262                }
2263            }
2264
2265            // Collect vendor overlay packages.
2266            // (Do this before scanning any apps.)
2267            // For security and version matching reason, only consider
2268            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2269            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2270            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2271                    | PackageParser.PARSE_IS_SYSTEM
2272                    | PackageParser.PARSE_IS_SYSTEM_DIR
2273                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2274
2275            // Find base frameworks (resource packages without code).
2276            scanDirTracedLI(frameworkDir, mDefParseFlags
2277                    | PackageParser.PARSE_IS_SYSTEM
2278                    | PackageParser.PARSE_IS_SYSTEM_DIR
2279                    | PackageParser.PARSE_IS_PRIVILEGED,
2280                    scanFlags | SCAN_NO_DEX, 0);
2281
2282            // Collected privileged system packages.
2283            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2284            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2285                    | PackageParser.PARSE_IS_SYSTEM
2286                    | PackageParser.PARSE_IS_SYSTEM_DIR
2287                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2288
2289            // Collect ordinary system packages.
2290            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2291            scanDirTracedLI(systemAppDir, mDefParseFlags
2292                    | PackageParser.PARSE_IS_SYSTEM
2293                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2294
2295            // Collect all vendor packages.
2296            File vendorAppDir = new File("/vendor/app");
2297            try {
2298                vendorAppDir = vendorAppDir.getCanonicalFile();
2299            } catch (IOException e) {
2300                // failed to look up canonical path, continue with original one
2301            }
2302            scanDirTracedLI(vendorAppDir, mDefParseFlags
2303                    | PackageParser.PARSE_IS_SYSTEM
2304                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2305
2306            // Collect all OEM packages.
2307            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2308            scanDirTracedLI(oemAppDir, mDefParseFlags
2309                    | PackageParser.PARSE_IS_SYSTEM
2310                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2311
2312            // Prune any system packages that no longer exist.
2313            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2314            if (!mOnlyCore) {
2315                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2316                while (psit.hasNext()) {
2317                    PackageSetting ps = psit.next();
2318
2319                    /*
2320                     * If this is not a system app, it can't be a
2321                     * disable system app.
2322                     */
2323                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2324                        continue;
2325                    }
2326
2327                    /*
2328                     * If the package is scanned, it's not erased.
2329                     */
2330                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2331                    if (scannedPkg != null) {
2332                        /*
2333                         * If the system app is both scanned and in the
2334                         * disabled packages list, then it must have been
2335                         * added via OTA. Remove it from the currently
2336                         * scanned package so the previously user-installed
2337                         * application can be scanned.
2338                         */
2339                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2340                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2341                                    + ps.name + "; removing system app.  Last known codePath="
2342                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2343                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2344                                    + scannedPkg.mVersionCode);
2345                            removePackageLI(scannedPkg, true);
2346                            mExpectingBetter.put(ps.name, ps.codePath);
2347                        }
2348
2349                        continue;
2350                    }
2351
2352                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2353                        psit.remove();
2354                        logCriticalInfo(Log.WARN, "System package " + ps.name
2355                                + " no longer exists; it's data will be wiped");
2356                        // Actual deletion of code and data will be handled by later
2357                        // reconciliation step
2358                    } else {
2359                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2360                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2361                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2362                        }
2363                    }
2364                }
2365            }
2366
2367            //look for any incomplete package installations
2368            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2369            for (int i = 0; i < deletePkgsList.size(); i++) {
2370                // Actual deletion of code and data will be handled by later
2371                // reconciliation step
2372                final String packageName = deletePkgsList.get(i).name;
2373                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2374                synchronized (mPackages) {
2375                    mSettings.removePackageLPw(packageName);
2376                }
2377            }
2378
2379            //delete tmp files
2380            deleteTempPackageFiles();
2381
2382            // Remove any shared userIDs that have no associated packages
2383            mSettings.pruneSharedUsersLPw();
2384
2385            if (!mOnlyCore) {
2386                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2387                        SystemClock.uptimeMillis());
2388                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2389
2390                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2391                        | PackageParser.PARSE_FORWARD_LOCK,
2392                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2393
2394                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2395                        | PackageParser.PARSE_IS_EPHEMERAL,
2396                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2397
2398                /**
2399                 * Remove disable package settings for any updated system
2400                 * apps that were removed via an OTA. If they're not a
2401                 * previously-updated app, remove them completely.
2402                 * Otherwise, just revoke their system-level permissions.
2403                 */
2404                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2405                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2406                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2407
2408                    String msg;
2409                    if (deletedPkg == null) {
2410                        msg = "Updated system package " + deletedAppName
2411                                + " no longer exists; it's data will be wiped";
2412                        // Actual deletion of code and data will be handled by later
2413                        // reconciliation step
2414                    } else {
2415                        msg = "Updated system app + " + deletedAppName
2416                                + " no longer present; removing system privileges for "
2417                                + deletedAppName;
2418
2419                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2420
2421                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2422                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2423                    }
2424                    logCriticalInfo(Log.WARN, msg);
2425                }
2426
2427                /**
2428                 * Make sure all system apps that we expected to appear on
2429                 * the userdata partition actually showed up. If they never
2430                 * appeared, crawl back and revive the system version.
2431                 */
2432                for (int i = 0; i < mExpectingBetter.size(); i++) {
2433                    final String packageName = mExpectingBetter.keyAt(i);
2434                    if (!mPackages.containsKey(packageName)) {
2435                        final File scanFile = mExpectingBetter.valueAt(i);
2436
2437                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2438                                + " but never showed up; reverting to system");
2439
2440                        int reparseFlags = mDefParseFlags;
2441                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2442                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2443                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2444                                    | PackageParser.PARSE_IS_PRIVILEGED;
2445                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2446                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2447                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2448                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2449                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2450                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2451                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2452                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2453                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2454                        } else {
2455                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2456                            continue;
2457                        }
2458
2459                        mSettings.enableSystemPackageLPw(packageName);
2460
2461                        try {
2462                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2463                        } catch (PackageManagerException e) {
2464                            Slog.e(TAG, "Failed to parse original system package: "
2465                                    + e.getMessage());
2466                        }
2467                    }
2468                }
2469            }
2470            mExpectingBetter.clear();
2471
2472            // Resolve protected action filters. Only the setup wizard is allowed to
2473            // have a high priority filter for these actions.
2474            mSetupWizardPackage = getSetupWizardPackageName();
2475            if (mProtectedFilters.size() > 0) {
2476                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2477                    Slog.i(TAG, "No setup wizard;"
2478                        + " All protected intents capped to priority 0");
2479                }
2480                for (ActivityIntentInfo filter : mProtectedFilters) {
2481                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2482                        if (DEBUG_FILTERS) {
2483                            Slog.i(TAG, "Found setup wizard;"
2484                                + " allow priority " + filter.getPriority() + ";"
2485                                + " package: " + filter.activity.info.packageName
2486                                + " activity: " + filter.activity.className
2487                                + " priority: " + filter.getPriority());
2488                        }
2489                        // skip setup wizard; allow it to keep the high priority filter
2490                        continue;
2491                    }
2492                    Slog.w(TAG, "Protected action; cap priority to 0;"
2493                            + " package: " + filter.activity.info.packageName
2494                            + " activity: " + filter.activity.className
2495                            + " origPrio: " + filter.getPriority());
2496                    filter.setPriority(0);
2497                }
2498            }
2499            mDeferProtectedFilters = false;
2500            mProtectedFilters.clear();
2501
2502            // Now that we know all of the shared libraries, update all clients to have
2503            // the correct library paths.
2504            updateAllSharedLibrariesLPw();
2505
2506            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2507                // NOTE: We ignore potential failures here during a system scan (like
2508                // the rest of the commands above) because there's precious little we
2509                // can do about it. A settings error is reported, though.
2510                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2511                        false /* boot complete */);
2512            }
2513
2514            // Now that we know all the packages we are keeping,
2515            // read and update their last usage times.
2516            mPackageUsage.read(mPackages);
2517            mCompilerStats.read();
2518
2519            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2520                    SystemClock.uptimeMillis());
2521            Slog.i(TAG, "Time to scan packages: "
2522                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2523                    + " seconds");
2524
2525            // If the platform SDK has changed since the last time we booted,
2526            // we need to re-grant app permission to catch any new ones that
2527            // appear.  This is really a hack, and means that apps can in some
2528            // cases get permissions that the user didn't initially explicitly
2529            // allow...  it would be nice to have some better way to handle
2530            // this situation.
2531            int updateFlags = UPDATE_PERMISSIONS_ALL;
2532            if (ver.sdkVersion != mSdkVersion) {
2533                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2534                        + mSdkVersion + "; regranting permissions for internal storage");
2535                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2536            }
2537            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2538            ver.sdkVersion = mSdkVersion;
2539
2540            // If this is the first boot or an update from pre-M, and it is a normal
2541            // boot, then we need to initialize the default preferred apps across
2542            // all defined users.
2543            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2544                for (UserInfo user : sUserManager.getUsers(true)) {
2545                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2546                    applyFactoryDefaultBrowserLPw(user.id);
2547                    primeDomainVerificationsLPw(user.id);
2548                }
2549            }
2550
2551            // Prepare storage for system user really early during boot,
2552            // since core system apps like SettingsProvider and SystemUI
2553            // can't wait for user to start
2554            final int storageFlags;
2555            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2556                storageFlags = StorageManager.FLAG_STORAGE_DE;
2557            } else {
2558                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2559            }
2560            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2561                    storageFlags, true /* migrateAppData */);
2562
2563            // If this is first boot after an OTA, and a normal boot, then
2564            // we need to clear code cache directories.
2565            // Note that we do *not* clear the application profiles. These remain valid
2566            // across OTAs and are used to drive profile verification (post OTA) and
2567            // profile compilation (without waiting to collect a fresh set of profiles).
2568            if (mIsUpgrade && !onlyCore) {
2569                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2570                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2571                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2572                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2573                        // No apps are running this early, so no need to freeze
2574                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2575                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2576                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2577                    }
2578                }
2579                ver.fingerprint = Build.FINGERPRINT;
2580            }
2581
2582            checkDefaultBrowser();
2583
2584            // clear only after permissions and other defaults have been updated
2585            mExistingSystemPackages.clear();
2586            mPromoteSystemApps = false;
2587
2588            // All the changes are done during package scanning.
2589            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2590
2591            // can downgrade to reader
2592            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2593            mSettings.writeLPr();
2594            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2595
2596            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2597            // early on (before the package manager declares itself as early) because other
2598            // components in the system server might ask for package contexts for these apps.
2599            //
2600            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2601            // (i.e, that the data partition is unavailable).
2602            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2603                long start = System.nanoTime();
2604                List<PackageParser.Package> coreApps = new ArrayList<>();
2605                for (PackageParser.Package pkg : mPackages.values()) {
2606                    if (pkg.coreApp) {
2607                        coreApps.add(pkg);
2608                    }
2609                }
2610
2611                int[] stats = performDexOptUpgrade(coreApps, false,
2612                        getCompilerFilterForReason(REASON_CORE_APP));
2613
2614                final int elapsedTimeSeconds =
2615                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2616                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2617
2618                if (DEBUG_DEXOPT) {
2619                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2620                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2621                }
2622
2623
2624                // TODO: Should we log these stats to tron too ?
2625                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2626                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2627                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2628                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2629            }
2630
2631            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2632                    SystemClock.uptimeMillis());
2633
2634            if (!mOnlyCore) {
2635                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2636                mRequiredInstallerPackage = getRequiredInstallerLPr();
2637                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2638                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2639                        mIntentFilterVerifierComponent);
2640                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2641                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2642                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2643                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2644            } else {
2645                mRequiredVerifierPackage = null;
2646                mRequiredInstallerPackage = null;
2647                mIntentFilterVerifierComponent = null;
2648                mIntentFilterVerifier = null;
2649                mServicesSystemSharedLibraryPackageName = null;
2650                mSharedSystemSharedLibraryPackageName = null;
2651            }
2652
2653            mInstallerService = new PackageInstallerService(context, this);
2654
2655            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2656            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2657            // both the installer and resolver must be present to enable ephemeral
2658            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2659                if (DEBUG_EPHEMERAL) {
2660                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2661                            + " installer:" + ephemeralInstallerComponent);
2662                }
2663                mEphemeralResolverComponent = ephemeralResolverComponent;
2664                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2665                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2666                mEphemeralResolverConnection =
2667                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2668            } else {
2669                if (DEBUG_EPHEMERAL) {
2670                    final String missingComponent =
2671                            (ephemeralResolverComponent == null)
2672                            ? (ephemeralInstallerComponent == null)
2673                                    ? "resolver and installer"
2674                                    : "resolver"
2675                            : "installer";
2676                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2677                }
2678                mEphemeralResolverComponent = null;
2679                mEphemeralInstallerComponent = null;
2680                mEphemeralResolverConnection = null;
2681            }
2682
2683            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2684        } // synchronized (mPackages)
2685        } // synchronized (mInstallLock)
2686
2687        // Now after opening every single application zip, make sure they
2688        // are all flushed.  Not really needed, but keeps things nice and
2689        // tidy.
2690        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
2691        Runtime.getRuntime().gc();
2692        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2693
2694        // The initial scanning above does many calls into installd while
2695        // holding the mPackages lock, but we're mostly interested in yelling
2696        // once we have a booted system.
2697        mInstaller.setWarnIfHeld(mPackages);
2698
2699        // Expose private service for system components to use.
2700        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2701        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2702    }
2703
2704    @Override
2705    public boolean isFirstBoot() {
2706        return mFirstBoot;
2707    }
2708
2709    @Override
2710    public boolean isOnlyCoreApps() {
2711        return mOnlyCore;
2712    }
2713
2714    @Override
2715    public boolean isUpgrade() {
2716        return mIsUpgrade;
2717    }
2718
2719    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2720        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2721
2722        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2723                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2724                UserHandle.USER_SYSTEM);
2725        if (matches.size() == 1) {
2726            return matches.get(0).getComponentInfo().packageName;
2727        } else {
2728            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2729            return null;
2730        }
2731    }
2732
2733    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2734        synchronized (mPackages) {
2735            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2736            if (libraryEntry == null) {
2737                throw new IllegalStateException("Missing required shared library:" + libraryName);
2738            }
2739            return libraryEntry.apk;
2740        }
2741    }
2742
2743    private @NonNull String getRequiredInstallerLPr() {
2744        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2745        intent.addCategory(Intent.CATEGORY_DEFAULT);
2746        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2747
2748        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2749                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2750                UserHandle.USER_SYSTEM);
2751        if (matches.size() == 1) {
2752            ResolveInfo resolveInfo = matches.get(0);
2753            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2754                throw new RuntimeException("The installer must be a privileged app");
2755            }
2756            return matches.get(0).getComponentInfo().packageName;
2757        } else {
2758            throw new RuntimeException("There must be exactly one installer; found " + matches);
2759        }
2760    }
2761
2762    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2763        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2764
2765        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2766                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2767                UserHandle.USER_SYSTEM);
2768        ResolveInfo best = null;
2769        final int N = matches.size();
2770        for (int i = 0; i < N; i++) {
2771            final ResolveInfo cur = matches.get(i);
2772            final String packageName = cur.getComponentInfo().packageName;
2773            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2774                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2775                continue;
2776            }
2777
2778            if (best == null || cur.priority > best.priority) {
2779                best = cur;
2780            }
2781        }
2782
2783        if (best != null) {
2784            return best.getComponentInfo().getComponentName();
2785        } else {
2786            throw new RuntimeException("There must be at least one intent filter verifier");
2787        }
2788    }
2789
2790    private @Nullable ComponentName getEphemeralResolverLPr() {
2791        final String[] packageArray =
2792                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2793        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2794            if (DEBUG_EPHEMERAL) {
2795                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2796            }
2797            return null;
2798        }
2799
2800        final int resolveFlags =
2801                MATCH_DIRECT_BOOT_AWARE
2802                | MATCH_DIRECT_BOOT_UNAWARE
2803                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2804        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2805        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2806                resolveFlags, UserHandle.USER_SYSTEM);
2807
2808        final int N = resolvers.size();
2809        if (N == 0) {
2810            if (DEBUG_EPHEMERAL) {
2811                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2812            }
2813            return null;
2814        }
2815
2816        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2817        for (int i = 0; i < N; i++) {
2818            final ResolveInfo info = resolvers.get(i);
2819
2820            if (info.serviceInfo == null) {
2821                continue;
2822            }
2823
2824            final String packageName = info.serviceInfo.packageName;
2825            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2826                if (DEBUG_EPHEMERAL) {
2827                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2828                            + " pkg: " + packageName + ", info:" + info);
2829                }
2830                continue;
2831            }
2832
2833            if (DEBUG_EPHEMERAL) {
2834                Slog.v(TAG, "Ephemeral resolver found;"
2835                        + " pkg: " + packageName + ", info:" + info);
2836            }
2837            return new ComponentName(packageName, info.serviceInfo.name);
2838        }
2839        if (DEBUG_EPHEMERAL) {
2840            Slog.v(TAG, "Ephemeral resolver NOT found");
2841        }
2842        return null;
2843    }
2844
2845    private @Nullable ComponentName getEphemeralInstallerLPr() {
2846        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2847        intent.addCategory(Intent.CATEGORY_DEFAULT);
2848        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2849
2850        final int resolveFlags =
2851                MATCH_DIRECT_BOOT_AWARE
2852                | MATCH_DIRECT_BOOT_UNAWARE
2853                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2854        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2855                resolveFlags, UserHandle.USER_SYSTEM);
2856        if (matches.size() == 0) {
2857            return null;
2858        } else if (matches.size() == 1) {
2859            return matches.get(0).getComponentInfo().getComponentName();
2860        } else {
2861            throw new RuntimeException(
2862                    "There must be at most one ephemeral installer; found " + matches);
2863        }
2864    }
2865
2866    private void primeDomainVerificationsLPw(int userId) {
2867        if (DEBUG_DOMAIN_VERIFICATION) {
2868            Slog.d(TAG, "Priming domain verifications in user " + userId);
2869        }
2870
2871        SystemConfig systemConfig = SystemConfig.getInstance();
2872        ArraySet<String> packages = systemConfig.getLinkedApps();
2873        ArraySet<String> domains = new ArraySet<String>();
2874
2875        for (String packageName : packages) {
2876            PackageParser.Package pkg = mPackages.get(packageName);
2877            if (pkg != null) {
2878                if (!pkg.isSystemApp()) {
2879                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2880                    continue;
2881                }
2882
2883                domains.clear();
2884                for (PackageParser.Activity a : pkg.activities) {
2885                    for (ActivityIntentInfo filter : a.intents) {
2886                        if (hasValidDomains(filter)) {
2887                            domains.addAll(filter.getHostsList());
2888                        }
2889                    }
2890                }
2891
2892                if (domains.size() > 0) {
2893                    if (DEBUG_DOMAIN_VERIFICATION) {
2894                        Slog.v(TAG, "      + " + packageName);
2895                    }
2896                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2897                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2898                    // and then 'always' in the per-user state actually used for intent resolution.
2899                    final IntentFilterVerificationInfo ivi;
2900                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2901                            new ArrayList<String>(domains));
2902                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2903                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2904                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2905                } else {
2906                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2907                            + "' does not handle web links");
2908                }
2909            } else {
2910                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2911            }
2912        }
2913
2914        scheduleWritePackageRestrictionsLocked(userId);
2915        scheduleWriteSettingsLocked();
2916    }
2917
2918    private void applyFactoryDefaultBrowserLPw(int userId) {
2919        // The default browser app's package name is stored in a string resource,
2920        // with a product-specific overlay used for vendor customization.
2921        String browserPkg = mContext.getResources().getString(
2922                com.android.internal.R.string.default_browser);
2923        if (!TextUtils.isEmpty(browserPkg)) {
2924            // non-empty string => required to be a known package
2925            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2926            if (ps == null) {
2927                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2928                browserPkg = null;
2929            } else {
2930                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2931            }
2932        }
2933
2934        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2935        // default.  If there's more than one, just leave everything alone.
2936        if (browserPkg == null) {
2937            calculateDefaultBrowserLPw(userId);
2938        }
2939    }
2940
2941    private void calculateDefaultBrowserLPw(int userId) {
2942        List<String> allBrowsers = resolveAllBrowserApps(userId);
2943        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2944        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2945    }
2946
2947    private List<String> resolveAllBrowserApps(int userId) {
2948        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2949        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2950                PackageManager.MATCH_ALL, userId);
2951
2952        final int count = list.size();
2953        List<String> result = new ArrayList<String>(count);
2954        for (int i=0; i<count; i++) {
2955            ResolveInfo info = list.get(i);
2956            if (info.activityInfo == null
2957                    || !info.handleAllWebDataURI
2958                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2959                    || result.contains(info.activityInfo.packageName)) {
2960                continue;
2961            }
2962            result.add(info.activityInfo.packageName);
2963        }
2964
2965        return result;
2966    }
2967
2968    private boolean packageIsBrowser(String packageName, int userId) {
2969        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2970                PackageManager.MATCH_ALL, userId);
2971        final int N = list.size();
2972        for (int i = 0; i < N; i++) {
2973            ResolveInfo info = list.get(i);
2974            if (packageName.equals(info.activityInfo.packageName)) {
2975                return true;
2976            }
2977        }
2978        return false;
2979    }
2980
2981    private void checkDefaultBrowser() {
2982        final int myUserId = UserHandle.myUserId();
2983        final String packageName = getDefaultBrowserPackageName(myUserId);
2984        if (packageName != null) {
2985            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2986            if (info == null) {
2987                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2988                synchronized (mPackages) {
2989                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2990                }
2991            }
2992        }
2993    }
2994
2995    @Override
2996    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2997            throws RemoteException {
2998        try {
2999            return super.onTransact(code, data, reply, flags);
3000        } catch (RuntimeException e) {
3001            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3002                Slog.wtf(TAG, "Package Manager Crash", e);
3003            }
3004            throw e;
3005        }
3006    }
3007
3008    static int[] appendInts(int[] cur, int[] add) {
3009        if (add == null) return cur;
3010        if (cur == null) return add;
3011        final int N = add.length;
3012        for (int i=0; i<N; i++) {
3013            cur = appendInt(cur, add[i]);
3014        }
3015        return cur;
3016    }
3017
3018    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3019        if (!sUserManager.exists(userId)) return null;
3020        if (ps == null) {
3021            return null;
3022        }
3023        final PackageParser.Package p = ps.pkg;
3024        if (p == null) {
3025            return null;
3026        }
3027
3028        final PermissionsState permissionsState = ps.getPermissionsState();
3029
3030        // Compute GIDs only if requested
3031        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3032                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3033        // Compute granted permissions only if package has requested permissions
3034        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3035                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3036        final PackageUserState state = ps.readUserState(userId);
3037
3038        return PackageParser.generatePackageInfo(p, gids, flags,
3039                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3040    }
3041
3042    @Override
3043    public void checkPackageStartable(String packageName, int userId) {
3044        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3045
3046        synchronized (mPackages) {
3047            final PackageSetting ps = mSettings.mPackages.get(packageName);
3048            if (ps == null) {
3049                throw new SecurityException("Package " + packageName + " was not found!");
3050            }
3051
3052            if (!ps.getInstalled(userId)) {
3053                throw new SecurityException(
3054                        "Package " + packageName + " was not installed for user " + userId + "!");
3055            }
3056
3057            if (mSafeMode && !ps.isSystem()) {
3058                throw new SecurityException("Package " + packageName + " not a system app!");
3059            }
3060
3061            if (mFrozenPackages.contains(packageName)) {
3062                throw new SecurityException("Package " + packageName + " is currently frozen!");
3063            }
3064
3065            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3066                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3067                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3068            }
3069        }
3070    }
3071
3072    @Override
3073    public boolean isPackageAvailable(String packageName, int userId) {
3074        if (!sUserManager.exists(userId)) return false;
3075        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3076                false /* requireFullPermission */, false /* checkShell */, "is package available");
3077        synchronized (mPackages) {
3078            PackageParser.Package p = mPackages.get(packageName);
3079            if (p != null) {
3080                final PackageSetting ps = (PackageSetting) p.mExtras;
3081                if (ps != null) {
3082                    final PackageUserState state = ps.readUserState(userId);
3083                    if (state != null) {
3084                        return PackageParser.isAvailable(state);
3085                    }
3086                }
3087            }
3088        }
3089        return false;
3090    }
3091
3092    @Override
3093    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3094        if (!sUserManager.exists(userId)) return null;
3095        flags = updateFlagsForPackage(flags, userId, packageName);
3096        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3097                false /* requireFullPermission */, false /* checkShell */, "get package info");
3098        // reader
3099        synchronized (mPackages) {
3100            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3101            PackageParser.Package p = null;
3102            if (matchFactoryOnly) {
3103                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3104                if (ps != null) {
3105                    return generatePackageInfo(ps, flags, userId);
3106                }
3107            }
3108            if (p == null) {
3109                p = mPackages.get(packageName);
3110                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3111                    return null;
3112                }
3113            }
3114            if (DEBUG_PACKAGE_INFO)
3115                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3116            if (p != null) {
3117                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3118            }
3119            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3120                final PackageSetting ps = mSettings.mPackages.get(packageName);
3121                return generatePackageInfo(ps, flags, userId);
3122            }
3123        }
3124        return null;
3125    }
3126
3127    @Override
3128    public String[] currentToCanonicalPackageNames(String[] names) {
3129        String[] out = new String[names.length];
3130        // reader
3131        synchronized (mPackages) {
3132            for (int i=names.length-1; i>=0; i--) {
3133                PackageSetting ps = mSettings.mPackages.get(names[i]);
3134                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3135            }
3136        }
3137        return out;
3138    }
3139
3140    @Override
3141    public String[] canonicalToCurrentPackageNames(String[] names) {
3142        String[] out = new String[names.length];
3143        // reader
3144        synchronized (mPackages) {
3145            for (int i=names.length-1; i>=0; i--) {
3146                String cur = mSettings.mRenamedPackages.get(names[i]);
3147                out[i] = cur != null ? cur : names[i];
3148            }
3149        }
3150        return out;
3151    }
3152
3153    @Override
3154    public int getPackageUid(String packageName, int flags, int userId) {
3155        if (!sUserManager.exists(userId)) return -1;
3156        flags = updateFlagsForPackage(flags, userId, packageName);
3157        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3158                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3159
3160        // reader
3161        synchronized (mPackages) {
3162            final PackageParser.Package p = mPackages.get(packageName);
3163            if (p != null && p.isMatch(flags)) {
3164                return UserHandle.getUid(userId, p.applicationInfo.uid);
3165            }
3166            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3167                final PackageSetting ps = mSettings.mPackages.get(packageName);
3168                if (ps != null && ps.isMatch(flags)) {
3169                    return UserHandle.getUid(userId, ps.appId);
3170                }
3171            }
3172        }
3173
3174        return -1;
3175    }
3176
3177    @Override
3178    public int[] getPackageGids(String packageName, int flags, int userId) {
3179        if (!sUserManager.exists(userId)) return null;
3180        flags = updateFlagsForPackage(flags, userId, packageName);
3181        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3182                false /* requireFullPermission */, false /* checkShell */,
3183                "getPackageGids");
3184
3185        // reader
3186        synchronized (mPackages) {
3187            final PackageParser.Package p = mPackages.get(packageName);
3188            if (p != null && p.isMatch(flags)) {
3189                PackageSetting ps = (PackageSetting) p.mExtras;
3190                return ps.getPermissionsState().computeGids(userId);
3191            }
3192            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3193                final PackageSetting ps = mSettings.mPackages.get(packageName);
3194                if (ps != null && ps.isMatch(flags)) {
3195                    return ps.getPermissionsState().computeGids(userId);
3196                }
3197            }
3198        }
3199
3200        return null;
3201    }
3202
3203    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3204        if (bp.perm != null) {
3205            return PackageParser.generatePermissionInfo(bp.perm, flags);
3206        }
3207        PermissionInfo pi = new PermissionInfo();
3208        pi.name = bp.name;
3209        pi.packageName = bp.sourcePackage;
3210        pi.nonLocalizedLabel = bp.name;
3211        pi.protectionLevel = bp.protectionLevel;
3212        return pi;
3213    }
3214
3215    @Override
3216    public PermissionInfo getPermissionInfo(String name, int flags) {
3217        // reader
3218        synchronized (mPackages) {
3219            final BasePermission p = mSettings.mPermissions.get(name);
3220            if (p != null) {
3221                return generatePermissionInfo(p, flags);
3222            }
3223            return null;
3224        }
3225    }
3226
3227    @Override
3228    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3229            int flags) {
3230        // reader
3231        synchronized (mPackages) {
3232            if (group != null && !mPermissionGroups.containsKey(group)) {
3233                // This is thrown as NameNotFoundException
3234                return null;
3235            }
3236
3237            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3238            for (BasePermission p : mSettings.mPermissions.values()) {
3239                if (group == null) {
3240                    if (p.perm == null || p.perm.info.group == null) {
3241                        out.add(generatePermissionInfo(p, flags));
3242                    }
3243                } else {
3244                    if (p.perm != null && group.equals(p.perm.info.group)) {
3245                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3246                    }
3247                }
3248            }
3249            return new ParceledListSlice<>(out);
3250        }
3251    }
3252
3253    @Override
3254    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3255        // reader
3256        synchronized (mPackages) {
3257            return PackageParser.generatePermissionGroupInfo(
3258                    mPermissionGroups.get(name), flags);
3259        }
3260    }
3261
3262    @Override
3263    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3264        // reader
3265        synchronized (mPackages) {
3266            final int N = mPermissionGroups.size();
3267            ArrayList<PermissionGroupInfo> out
3268                    = new ArrayList<PermissionGroupInfo>(N);
3269            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3270                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3271            }
3272            return new ParceledListSlice<>(out);
3273        }
3274    }
3275
3276    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3277            int userId) {
3278        if (!sUserManager.exists(userId)) return null;
3279        PackageSetting ps = mSettings.mPackages.get(packageName);
3280        if (ps != null) {
3281            if (ps.pkg == null) {
3282                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3283                if (pInfo != null) {
3284                    return pInfo.applicationInfo;
3285                }
3286                return null;
3287            }
3288            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3289                    ps.readUserState(userId), userId);
3290        }
3291        return null;
3292    }
3293
3294    @Override
3295    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3296        if (!sUserManager.exists(userId)) return null;
3297        flags = updateFlagsForApplication(flags, userId, packageName);
3298        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3299                false /* requireFullPermission */, false /* checkShell */, "get application info");
3300        // writer
3301        synchronized (mPackages) {
3302            PackageParser.Package p = mPackages.get(packageName);
3303            if (DEBUG_PACKAGE_INFO) Log.v(
3304                    TAG, "getApplicationInfo " + packageName
3305                    + ": " + p);
3306            if (p != null) {
3307                PackageSetting ps = mSettings.mPackages.get(packageName);
3308                if (ps == null) return null;
3309                // Note: isEnabledLP() does not apply here - always return info
3310                return PackageParser.generateApplicationInfo(
3311                        p, flags, ps.readUserState(userId), userId);
3312            }
3313            if ("android".equals(packageName)||"system".equals(packageName)) {
3314                return mAndroidApplication;
3315            }
3316            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3317                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3318            }
3319        }
3320        return null;
3321    }
3322
3323    @Override
3324    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3325            final IPackageDataObserver observer) {
3326        mContext.enforceCallingOrSelfPermission(
3327                android.Manifest.permission.CLEAR_APP_CACHE, null);
3328        // Queue up an async operation since clearing cache may take a little while.
3329        mHandler.post(new Runnable() {
3330            public void run() {
3331                mHandler.removeCallbacks(this);
3332                boolean success = true;
3333                synchronized (mInstallLock) {
3334                    try {
3335                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3336                    } catch (InstallerException e) {
3337                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3338                        success = false;
3339                    }
3340                }
3341                if (observer != null) {
3342                    try {
3343                        observer.onRemoveCompleted(null, success);
3344                    } catch (RemoteException e) {
3345                        Slog.w(TAG, "RemoveException when invoking call back");
3346                    }
3347                }
3348            }
3349        });
3350    }
3351
3352    @Override
3353    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3354            final IntentSender pi) {
3355        mContext.enforceCallingOrSelfPermission(
3356                android.Manifest.permission.CLEAR_APP_CACHE, null);
3357        // Queue up an async operation since clearing cache may take a little while.
3358        mHandler.post(new Runnable() {
3359            public void run() {
3360                mHandler.removeCallbacks(this);
3361                boolean success = true;
3362                synchronized (mInstallLock) {
3363                    try {
3364                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3365                    } catch (InstallerException e) {
3366                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3367                        success = false;
3368                    }
3369                }
3370                if(pi != null) {
3371                    try {
3372                        // Callback via pending intent
3373                        int code = success ? 1 : 0;
3374                        pi.sendIntent(null, code, null,
3375                                null, null);
3376                    } catch (SendIntentException e1) {
3377                        Slog.i(TAG, "Failed to send pending intent");
3378                    }
3379                }
3380            }
3381        });
3382    }
3383
3384    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3385        synchronized (mInstallLock) {
3386            try {
3387                mInstaller.freeCache(volumeUuid, freeStorageSize);
3388            } catch (InstallerException e) {
3389                throw new IOException("Failed to free enough space", e);
3390            }
3391        }
3392    }
3393
3394    /**
3395     * Update given flags based on encryption status of current user.
3396     */
3397    private int updateFlags(int flags, int userId) {
3398        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3399                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3400            // Caller expressed an explicit opinion about what encryption
3401            // aware/unaware components they want to see, so fall through and
3402            // give them what they want
3403        } else {
3404            // Caller expressed no opinion, so match based on user state
3405            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3406                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3407            } else {
3408                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3409            }
3410        }
3411        return flags;
3412    }
3413
3414    private UserManagerInternal getUserManagerInternal() {
3415        if (mUserManagerInternal == null) {
3416            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3417        }
3418        return mUserManagerInternal;
3419    }
3420
3421    /**
3422     * Update given flags when being used to request {@link PackageInfo}.
3423     */
3424    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3425        boolean triaged = true;
3426        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3427                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3428            // Caller is asking for component details, so they'd better be
3429            // asking for specific encryption matching behavior, or be triaged
3430            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3431                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3432                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3433                triaged = false;
3434            }
3435        }
3436        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3437                | PackageManager.MATCH_SYSTEM_ONLY
3438                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3439            triaged = false;
3440        }
3441        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3442            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3443                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3444        }
3445        return updateFlags(flags, userId);
3446    }
3447
3448    /**
3449     * Update given flags when being used to request {@link ApplicationInfo}.
3450     */
3451    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3452        return updateFlagsForPackage(flags, userId, cookie);
3453    }
3454
3455    /**
3456     * Update given flags when being used to request {@link ComponentInfo}.
3457     */
3458    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3459        if (cookie instanceof Intent) {
3460            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3461                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3462            }
3463        }
3464
3465        boolean triaged = true;
3466        // Caller is asking for component details, so they'd better be
3467        // asking for specific encryption matching behavior, or be triaged
3468        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3469                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3470                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3471            triaged = false;
3472        }
3473        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3474            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3475                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3476        }
3477
3478        return updateFlags(flags, userId);
3479    }
3480
3481    /**
3482     * Update given flags when being used to request {@link ResolveInfo}.
3483     */
3484    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3485        // Safe mode means we shouldn't match any third-party components
3486        if (mSafeMode) {
3487            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3488        }
3489
3490        return updateFlagsForComponent(flags, userId, cookie);
3491    }
3492
3493    @Override
3494    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3495        if (!sUserManager.exists(userId)) return null;
3496        flags = updateFlagsForComponent(flags, userId, component);
3497        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3498                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3499        synchronized (mPackages) {
3500            PackageParser.Activity a = mActivities.mActivities.get(component);
3501
3502            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3503            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3504                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3505                if (ps == null) return null;
3506                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3507                        userId);
3508            }
3509            if (mResolveComponentName.equals(component)) {
3510                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3511                        new PackageUserState(), userId);
3512            }
3513        }
3514        return null;
3515    }
3516
3517    @Override
3518    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3519            String resolvedType) {
3520        synchronized (mPackages) {
3521            if (component.equals(mResolveComponentName)) {
3522                // The resolver supports EVERYTHING!
3523                return true;
3524            }
3525            PackageParser.Activity a = mActivities.mActivities.get(component);
3526            if (a == null) {
3527                return false;
3528            }
3529            for (int i=0; i<a.intents.size(); i++) {
3530                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3531                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3532                    return true;
3533                }
3534            }
3535            return false;
3536        }
3537    }
3538
3539    @Override
3540    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3541        if (!sUserManager.exists(userId)) return null;
3542        flags = updateFlagsForComponent(flags, userId, component);
3543        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3544                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3545        synchronized (mPackages) {
3546            PackageParser.Activity a = mReceivers.mActivities.get(component);
3547            if (DEBUG_PACKAGE_INFO) Log.v(
3548                TAG, "getReceiverInfo " + component + ": " + a);
3549            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3550                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3551                if (ps == null) return null;
3552                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3553                        userId);
3554            }
3555        }
3556        return null;
3557    }
3558
3559    @Override
3560    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3561        if (!sUserManager.exists(userId)) return null;
3562        flags = updateFlagsForComponent(flags, userId, component);
3563        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3564                false /* requireFullPermission */, false /* checkShell */, "get service info");
3565        synchronized (mPackages) {
3566            PackageParser.Service s = mServices.mServices.get(component);
3567            if (DEBUG_PACKAGE_INFO) Log.v(
3568                TAG, "getServiceInfo " + component + ": " + s);
3569            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3570                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3571                if (ps == null) return null;
3572                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3573                        userId);
3574            }
3575        }
3576        return null;
3577    }
3578
3579    @Override
3580    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3581        if (!sUserManager.exists(userId)) return null;
3582        flags = updateFlagsForComponent(flags, userId, component);
3583        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3584                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3585        synchronized (mPackages) {
3586            PackageParser.Provider p = mProviders.mProviders.get(component);
3587            if (DEBUG_PACKAGE_INFO) Log.v(
3588                TAG, "getProviderInfo " + component + ": " + p);
3589            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3590                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3591                if (ps == null) return null;
3592                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3593                        userId);
3594            }
3595        }
3596        return null;
3597    }
3598
3599    @Override
3600    public String[] getSystemSharedLibraryNames() {
3601        Set<String> libSet;
3602        synchronized (mPackages) {
3603            libSet = mSharedLibraries.keySet();
3604            int size = libSet.size();
3605            if (size > 0) {
3606                String[] libs = new String[size];
3607                libSet.toArray(libs);
3608                return libs;
3609            }
3610        }
3611        return null;
3612    }
3613
3614    @Override
3615    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3616        synchronized (mPackages) {
3617            return mServicesSystemSharedLibraryPackageName;
3618        }
3619    }
3620
3621    @Override
3622    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3623        synchronized (mPackages) {
3624            return mSharedSystemSharedLibraryPackageName;
3625        }
3626    }
3627
3628    @Override
3629    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3630        synchronized (mPackages) {
3631            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3632
3633            final FeatureInfo fi = new FeatureInfo();
3634            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3635                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3636            res.add(fi);
3637
3638            return new ParceledListSlice<>(res);
3639        }
3640    }
3641
3642    @Override
3643    public boolean hasSystemFeature(String name, int version) {
3644        synchronized (mPackages) {
3645            final FeatureInfo feat = mAvailableFeatures.get(name);
3646            if (feat == null) {
3647                return false;
3648            } else {
3649                return feat.version >= version;
3650            }
3651        }
3652    }
3653
3654    @Override
3655    public int checkPermission(String permName, String pkgName, int userId) {
3656        if (!sUserManager.exists(userId)) {
3657            return PackageManager.PERMISSION_DENIED;
3658        }
3659
3660        synchronized (mPackages) {
3661            final PackageParser.Package p = mPackages.get(pkgName);
3662            if (p != null && p.mExtras != null) {
3663                final PackageSetting ps = (PackageSetting) p.mExtras;
3664                final PermissionsState permissionsState = ps.getPermissionsState();
3665                if (permissionsState.hasPermission(permName, userId)) {
3666                    return PackageManager.PERMISSION_GRANTED;
3667                }
3668                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3669                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3670                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3671                    return PackageManager.PERMISSION_GRANTED;
3672                }
3673            }
3674        }
3675
3676        return PackageManager.PERMISSION_DENIED;
3677    }
3678
3679    @Override
3680    public int checkUidPermission(String permName, int uid) {
3681        final int userId = UserHandle.getUserId(uid);
3682
3683        if (!sUserManager.exists(userId)) {
3684            return PackageManager.PERMISSION_DENIED;
3685        }
3686
3687        synchronized (mPackages) {
3688            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3689            if (obj != null) {
3690                final SettingBase ps = (SettingBase) obj;
3691                final PermissionsState permissionsState = ps.getPermissionsState();
3692                if (permissionsState.hasPermission(permName, userId)) {
3693                    return PackageManager.PERMISSION_GRANTED;
3694                }
3695                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3696                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3697                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3698                    return PackageManager.PERMISSION_GRANTED;
3699                }
3700            } else {
3701                ArraySet<String> perms = mSystemPermissions.get(uid);
3702                if (perms != null) {
3703                    if (perms.contains(permName)) {
3704                        return PackageManager.PERMISSION_GRANTED;
3705                    }
3706                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3707                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3708                        return PackageManager.PERMISSION_GRANTED;
3709                    }
3710                }
3711            }
3712        }
3713
3714        return PackageManager.PERMISSION_DENIED;
3715    }
3716
3717    @Override
3718    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3719        if (UserHandle.getCallingUserId() != userId) {
3720            mContext.enforceCallingPermission(
3721                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3722                    "isPermissionRevokedByPolicy for user " + userId);
3723        }
3724
3725        if (checkPermission(permission, packageName, userId)
3726                == PackageManager.PERMISSION_GRANTED) {
3727            return false;
3728        }
3729
3730        final long identity = Binder.clearCallingIdentity();
3731        try {
3732            final int flags = getPermissionFlags(permission, packageName, userId);
3733            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3734        } finally {
3735            Binder.restoreCallingIdentity(identity);
3736        }
3737    }
3738
3739    @Override
3740    public String getPermissionControllerPackageName() {
3741        synchronized (mPackages) {
3742            return mRequiredInstallerPackage;
3743        }
3744    }
3745
3746    /**
3747     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3748     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3749     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3750     * @param message the message to log on security exception
3751     */
3752    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3753            boolean checkShell, String message) {
3754        if (userId < 0) {
3755            throw new IllegalArgumentException("Invalid userId " + userId);
3756        }
3757        if (checkShell) {
3758            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3759        }
3760        if (userId == UserHandle.getUserId(callingUid)) return;
3761        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3762            if (requireFullPermission) {
3763                mContext.enforceCallingOrSelfPermission(
3764                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3765            } else {
3766                try {
3767                    mContext.enforceCallingOrSelfPermission(
3768                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3769                } catch (SecurityException se) {
3770                    mContext.enforceCallingOrSelfPermission(
3771                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3772                }
3773            }
3774        }
3775    }
3776
3777    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3778        if (callingUid == Process.SHELL_UID) {
3779            if (userHandle >= 0
3780                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3781                throw new SecurityException("Shell does not have permission to access user "
3782                        + userHandle);
3783            } else if (userHandle < 0) {
3784                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3785                        + Debug.getCallers(3));
3786            }
3787        }
3788    }
3789
3790    private BasePermission findPermissionTreeLP(String permName) {
3791        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3792            if (permName.startsWith(bp.name) &&
3793                    permName.length() > bp.name.length() &&
3794                    permName.charAt(bp.name.length()) == '.') {
3795                return bp;
3796            }
3797        }
3798        return null;
3799    }
3800
3801    private BasePermission checkPermissionTreeLP(String permName) {
3802        if (permName != null) {
3803            BasePermission bp = findPermissionTreeLP(permName);
3804            if (bp != null) {
3805                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3806                    return bp;
3807                }
3808                throw new SecurityException("Calling uid "
3809                        + Binder.getCallingUid()
3810                        + " is not allowed to add to permission tree "
3811                        + bp.name + " owned by uid " + bp.uid);
3812            }
3813        }
3814        throw new SecurityException("No permission tree found for " + permName);
3815    }
3816
3817    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3818        if (s1 == null) {
3819            return s2 == null;
3820        }
3821        if (s2 == null) {
3822            return false;
3823        }
3824        if (s1.getClass() != s2.getClass()) {
3825            return false;
3826        }
3827        return s1.equals(s2);
3828    }
3829
3830    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3831        if (pi1.icon != pi2.icon) return false;
3832        if (pi1.logo != pi2.logo) return false;
3833        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3834        if (!compareStrings(pi1.name, pi2.name)) return false;
3835        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3836        // We'll take care of setting this one.
3837        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3838        // These are not currently stored in settings.
3839        //if (!compareStrings(pi1.group, pi2.group)) return false;
3840        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3841        //if (pi1.labelRes != pi2.labelRes) return false;
3842        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3843        return true;
3844    }
3845
3846    int permissionInfoFootprint(PermissionInfo info) {
3847        int size = info.name.length();
3848        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3849        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3850        return size;
3851    }
3852
3853    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3854        int size = 0;
3855        for (BasePermission perm : mSettings.mPermissions.values()) {
3856            if (perm.uid == tree.uid) {
3857                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3858            }
3859        }
3860        return size;
3861    }
3862
3863    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3864        // We calculate the max size of permissions defined by this uid and throw
3865        // if that plus the size of 'info' would exceed our stated maximum.
3866        if (tree.uid != Process.SYSTEM_UID) {
3867            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3868            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3869                throw new SecurityException("Permission tree size cap exceeded");
3870            }
3871        }
3872    }
3873
3874    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3875        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3876            throw new SecurityException("Label must be specified in permission");
3877        }
3878        BasePermission tree = checkPermissionTreeLP(info.name);
3879        BasePermission bp = mSettings.mPermissions.get(info.name);
3880        boolean added = bp == null;
3881        boolean changed = true;
3882        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3883        if (added) {
3884            enforcePermissionCapLocked(info, tree);
3885            bp = new BasePermission(info.name, tree.sourcePackage,
3886                    BasePermission.TYPE_DYNAMIC);
3887        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3888            throw new SecurityException(
3889                    "Not allowed to modify non-dynamic permission "
3890                    + info.name);
3891        } else {
3892            if (bp.protectionLevel == fixedLevel
3893                    && bp.perm.owner.equals(tree.perm.owner)
3894                    && bp.uid == tree.uid
3895                    && comparePermissionInfos(bp.perm.info, info)) {
3896                changed = false;
3897            }
3898        }
3899        bp.protectionLevel = fixedLevel;
3900        info = new PermissionInfo(info);
3901        info.protectionLevel = fixedLevel;
3902        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3903        bp.perm.info.packageName = tree.perm.info.packageName;
3904        bp.uid = tree.uid;
3905        if (added) {
3906            mSettings.mPermissions.put(info.name, bp);
3907        }
3908        if (changed) {
3909            if (!async) {
3910                mSettings.writeLPr();
3911            } else {
3912                scheduleWriteSettingsLocked();
3913            }
3914        }
3915        return added;
3916    }
3917
3918    @Override
3919    public boolean addPermission(PermissionInfo info) {
3920        synchronized (mPackages) {
3921            return addPermissionLocked(info, false);
3922        }
3923    }
3924
3925    @Override
3926    public boolean addPermissionAsync(PermissionInfo info) {
3927        synchronized (mPackages) {
3928            return addPermissionLocked(info, true);
3929        }
3930    }
3931
3932    @Override
3933    public void removePermission(String name) {
3934        synchronized (mPackages) {
3935            checkPermissionTreeLP(name);
3936            BasePermission bp = mSettings.mPermissions.get(name);
3937            if (bp != null) {
3938                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3939                    throw new SecurityException(
3940                            "Not allowed to modify non-dynamic permission "
3941                            + name);
3942                }
3943                mSettings.mPermissions.remove(name);
3944                mSettings.writeLPr();
3945            }
3946        }
3947    }
3948
3949    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3950            BasePermission bp) {
3951        int index = pkg.requestedPermissions.indexOf(bp.name);
3952        if (index == -1) {
3953            throw new SecurityException("Package " + pkg.packageName
3954                    + " has not requested permission " + bp.name);
3955        }
3956        if (!bp.isRuntime() && !bp.isDevelopment()) {
3957            throw new SecurityException("Permission " + bp.name
3958                    + " is not a changeable permission type");
3959        }
3960    }
3961
3962    @Override
3963    public void grantRuntimePermission(String packageName, String name, final int userId) {
3964        if (!sUserManager.exists(userId)) {
3965            Log.e(TAG, "No such user:" + userId);
3966            return;
3967        }
3968
3969        mContext.enforceCallingOrSelfPermission(
3970                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3971                "grantRuntimePermission");
3972
3973        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3974                true /* requireFullPermission */, true /* checkShell */,
3975                "grantRuntimePermission");
3976
3977        final int uid;
3978        final SettingBase sb;
3979
3980        synchronized (mPackages) {
3981            final PackageParser.Package pkg = mPackages.get(packageName);
3982            if (pkg == null) {
3983                throw new IllegalArgumentException("Unknown package: " + packageName);
3984            }
3985
3986            final BasePermission bp = mSettings.mPermissions.get(name);
3987            if (bp == null) {
3988                throw new IllegalArgumentException("Unknown permission: " + name);
3989            }
3990
3991            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3992
3993            // If a permission review is required for legacy apps we represent
3994            // their permissions as always granted runtime ones since we need
3995            // to keep the review required permission flag per user while an
3996            // install permission's state is shared across all users.
3997            if (Build.PERMISSIONS_REVIEW_REQUIRED
3998                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3999                    && bp.isRuntime()) {
4000                return;
4001            }
4002
4003            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4004            sb = (SettingBase) pkg.mExtras;
4005            if (sb == null) {
4006                throw new IllegalArgumentException("Unknown package: " + packageName);
4007            }
4008
4009            final PermissionsState permissionsState = sb.getPermissionsState();
4010
4011            final int flags = permissionsState.getPermissionFlags(name, userId);
4012            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4013                throw new SecurityException("Cannot grant system fixed permission "
4014                        + name + " for package " + packageName);
4015            }
4016
4017            if (bp.isDevelopment()) {
4018                // Development permissions must be handled specially, since they are not
4019                // normal runtime permissions.  For now they apply to all users.
4020                if (permissionsState.grantInstallPermission(bp) !=
4021                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4022                    scheduleWriteSettingsLocked();
4023                }
4024                return;
4025            }
4026
4027            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4028                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4029                return;
4030            }
4031
4032            final int result = permissionsState.grantRuntimePermission(bp, userId);
4033            switch (result) {
4034                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4035                    return;
4036                }
4037
4038                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4039                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4040                    mHandler.post(new Runnable() {
4041                        @Override
4042                        public void run() {
4043                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4044                        }
4045                    });
4046                }
4047                break;
4048            }
4049
4050            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4051
4052            // Not critical if that is lost - app has to request again.
4053            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4054        }
4055
4056        // Only need to do this if user is initialized. Otherwise it's a new user
4057        // and there are no processes running as the user yet and there's no need
4058        // to make an expensive call to remount processes for the changed permissions.
4059        if (READ_EXTERNAL_STORAGE.equals(name)
4060                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4061            final long token = Binder.clearCallingIdentity();
4062            try {
4063                if (sUserManager.isInitialized(userId)) {
4064                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4065                            MountServiceInternal.class);
4066                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4067                }
4068            } finally {
4069                Binder.restoreCallingIdentity(token);
4070            }
4071        }
4072    }
4073
4074    @Override
4075    public void revokeRuntimePermission(String packageName, String name, int userId) {
4076        if (!sUserManager.exists(userId)) {
4077            Log.e(TAG, "No such user:" + userId);
4078            return;
4079        }
4080
4081        mContext.enforceCallingOrSelfPermission(
4082                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4083                "revokeRuntimePermission");
4084
4085        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4086                true /* requireFullPermission */, true /* checkShell */,
4087                "revokeRuntimePermission");
4088
4089        final int appId;
4090
4091        synchronized (mPackages) {
4092            final PackageParser.Package pkg = mPackages.get(packageName);
4093            if (pkg == null) {
4094                throw new IllegalArgumentException("Unknown package: " + packageName);
4095            }
4096
4097            final BasePermission bp = mSettings.mPermissions.get(name);
4098            if (bp == null) {
4099                throw new IllegalArgumentException("Unknown permission: " + name);
4100            }
4101
4102            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4103
4104            // If a permission review is required for legacy apps we represent
4105            // their permissions as always granted runtime ones since we need
4106            // to keep the review required permission flag per user while an
4107            // install permission's state is shared across all users.
4108            if (Build.PERMISSIONS_REVIEW_REQUIRED
4109                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4110                    && bp.isRuntime()) {
4111                return;
4112            }
4113
4114            SettingBase sb = (SettingBase) pkg.mExtras;
4115            if (sb == null) {
4116                throw new IllegalArgumentException("Unknown package: " + packageName);
4117            }
4118
4119            final PermissionsState permissionsState = sb.getPermissionsState();
4120
4121            final int flags = permissionsState.getPermissionFlags(name, userId);
4122            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4123                throw new SecurityException("Cannot revoke system fixed permission "
4124                        + name + " for package " + packageName);
4125            }
4126
4127            if (bp.isDevelopment()) {
4128                // Development permissions must be handled specially, since they are not
4129                // normal runtime permissions.  For now they apply to all users.
4130                if (permissionsState.revokeInstallPermission(bp) !=
4131                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4132                    scheduleWriteSettingsLocked();
4133                }
4134                return;
4135            }
4136
4137            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4138                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4139                return;
4140            }
4141
4142            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4143
4144            // Critical, after this call app should never have the permission.
4145            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4146
4147            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4148        }
4149
4150        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4151    }
4152
4153    @Override
4154    public void resetRuntimePermissions() {
4155        mContext.enforceCallingOrSelfPermission(
4156                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4157                "revokeRuntimePermission");
4158
4159        int callingUid = Binder.getCallingUid();
4160        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4161            mContext.enforceCallingOrSelfPermission(
4162                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4163                    "resetRuntimePermissions");
4164        }
4165
4166        synchronized (mPackages) {
4167            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4168            for (int userId : UserManagerService.getInstance().getUserIds()) {
4169                final int packageCount = mPackages.size();
4170                for (int i = 0; i < packageCount; i++) {
4171                    PackageParser.Package pkg = mPackages.valueAt(i);
4172                    if (!(pkg.mExtras instanceof PackageSetting)) {
4173                        continue;
4174                    }
4175                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4176                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4177                }
4178            }
4179        }
4180    }
4181
4182    @Override
4183    public int getPermissionFlags(String name, String packageName, int userId) {
4184        if (!sUserManager.exists(userId)) {
4185            return 0;
4186        }
4187
4188        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4189
4190        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4191                true /* requireFullPermission */, false /* checkShell */,
4192                "getPermissionFlags");
4193
4194        synchronized (mPackages) {
4195            final PackageParser.Package pkg = mPackages.get(packageName);
4196            if (pkg == null) {
4197                return 0;
4198            }
4199
4200            final BasePermission bp = mSettings.mPermissions.get(name);
4201            if (bp == null) {
4202                return 0;
4203            }
4204
4205            SettingBase sb = (SettingBase) pkg.mExtras;
4206            if (sb == null) {
4207                return 0;
4208            }
4209
4210            PermissionsState permissionsState = sb.getPermissionsState();
4211            return permissionsState.getPermissionFlags(name, userId);
4212        }
4213    }
4214
4215    @Override
4216    public void updatePermissionFlags(String name, String packageName, int flagMask,
4217            int flagValues, int userId) {
4218        if (!sUserManager.exists(userId)) {
4219            return;
4220        }
4221
4222        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4223
4224        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4225                true /* requireFullPermission */, true /* checkShell */,
4226                "updatePermissionFlags");
4227
4228        // Only the system can change these flags and nothing else.
4229        if (getCallingUid() != Process.SYSTEM_UID) {
4230            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4231            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4232            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4233            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4234            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4235        }
4236
4237        synchronized (mPackages) {
4238            final PackageParser.Package pkg = mPackages.get(packageName);
4239            if (pkg == null) {
4240                throw new IllegalArgumentException("Unknown package: " + packageName);
4241            }
4242
4243            final BasePermission bp = mSettings.mPermissions.get(name);
4244            if (bp == null) {
4245                throw new IllegalArgumentException("Unknown permission: " + name);
4246            }
4247
4248            SettingBase sb = (SettingBase) pkg.mExtras;
4249            if (sb == null) {
4250                throw new IllegalArgumentException("Unknown package: " + packageName);
4251            }
4252
4253            PermissionsState permissionsState = sb.getPermissionsState();
4254
4255            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4256
4257            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4258                // Install and runtime permissions are stored in different places,
4259                // so figure out what permission changed and persist the change.
4260                if (permissionsState.getInstallPermissionState(name) != null) {
4261                    scheduleWriteSettingsLocked();
4262                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4263                        || hadState) {
4264                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4265                }
4266            }
4267        }
4268    }
4269
4270    /**
4271     * Update the permission flags for all packages and runtime permissions of a user in order
4272     * to allow device or profile owner to remove POLICY_FIXED.
4273     */
4274    @Override
4275    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4276        if (!sUserManager.exists(userId)) {
4277            return;
4278        }
4279
4280        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4281
4282        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4283                true /* requireFullPermission */, true /* checkShell */,
4284                "updatePermissionFlagsForAllApps");
4285
4286        // Only the system can change system fixed flags.
4287        if (getCallingUid() != Process.SYSTEM_UID) {
4288            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4289            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4290        }
4291
4292        synchronized (mPackages) {
4293            boolean changed = false;
4294            final int packageCount = mPackages.size();
4295            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4296                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4297                SettingBase sb = (SettingBase) pkg.mExtras;
4298                if (sb == null) {
4299                    continue;
4300                }
4301                PermissionsState permissionsState = sb.getPermissionsState();
4302                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4303                        userId, flagMask, flagValues);
4304            }
4305            if (changed) {
4306                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4307            }
4308        }
4309    }
4310
4311    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4312        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4313                != PackageManager.PERMISSION_GRANTED
4314            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4315                != PackageManager.PERMISSION_GRANTED) {
4316            throw new SecurityException(message + " requires "
4317                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4318                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4319        }
4320    }
4321
4322    @Override
4323    public boolean shouldShowRequestPermissionRationale(String permissionName,
4324            String packageName, int userId) {
4325        if (UserHandle.getCallingUserId() != userId) {
4326            mContext.enforceCallingPermission(
4327                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4328                    "canShowRequestPermissionRationale for user " + userId);
4329        }
4330
4331        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4332        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4333            return false;
4334        }
4335
4336        if (checkPermission(permissionName, packageName, userId)
4337                == PackageManager.PERMISSION_GRANTED) {
4338            return false;
4339        }
4340
4341        final int flags;
4342
4343        final long identity = Binder.clearCallingIdentity();
4344        try {
4345            flags = getPermissionFlags(permissionName,
4346                    packageName, userId);
4347        } finally {
4348            Binder.restoreCallingIdentity(identity);
4349        }
4350
4351        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4352                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4353                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4354
4355        if ((flags & fixedFlags) != 0) {
4356            return false;
4357        }
4358
4359        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4360    }
4361
4362    @Override
4363    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4364        mContext.enforceCallingOrSelfPermission(
4365                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4366                "addOnPermissionsChangeListener");
4367
4368        synchronized (mPackages) {
4369            mOnPermissionChangeListeners.addListenerLocked(listener);
4370        }
4371    }
4372
4373    @Override
4374    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4375        synchronized (mPackages) {
4376            mOnPermissionChangeListeners.removeListenerLocked(listener);
4377        }
4378    }
4379
4380    @Override
4381    public boolean isProtectedBroadcast(String actionName) {
4382        synchronized (mPackages) {
4383            if (mProtectedBroadcasts.contains(actionName)) {
4384                return true;
4385            } else if (actionName != null) {
4386                // TODO: remove these terrible hacks
4387                if (actionName.startsWith("android.net.netmon.lingerExpired")
4388                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4389                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4390                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4391                    return true;
4392                }
4393            }
4394        }
4395        return false;
4396    }
4397
4398    @Override
4399    public int checkSignatures(String pkg1, String pkg2) {
4400        synchronized (mPackages) {
4401            final PackageParser.Package p1 = mPackages.get(pkg1);
4402            final PackageParser.Package p2 = mPackages.get(pkg2);
4403            if (p1 == null || p1.mExtras == null
4404                    || p2 == null || p2.mExtras == null) {
4405                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4406            }
4407            return compareSignatures(p1.mSignatures, p2.mSignatures);
4408        }
4409    }
4410
4411    @Override
4412    public int checkUidSignatures(int uid1, int uid2) {
4413        // Map to base uids.
4414        uid1 = UserHandle.getAppId(uid1);
4415        uid2 = UserHandle.getAppId(uid2);
4416        // reader
4417        synchronized (mPackages) {
4418            Signature[] s1;
4419            Signature[] s2;
4420            Object obj = mSettings.getUserIdLPr(uid1);
4421            if (obj != null) {
4422                if (obj instanceof SharedUserSetting) {
4423                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4424                } else if (obj instanceof PackageSetting) {
4425                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4426                } else {
4427                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4428                }
4429            } else {
4430                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4431            }
4432            obj = mSettings.getUserIdLPr(uid2);
4433            if (obj != null) {
4434                if (obj instanceof SharedUserSetting) {
4435                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4436                } else if (obj instanceof PackageSetting) {
4437                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4438                } else {
4439                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4440                }
4441            } else {
4442                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4443            }
4444            return compareSignatures(s1, s2);
4445        }
4446    }
4447
4448    /**
4449     * This method should typically only be used when granting or revoking
4450     * permissions, since the app may immediately restart after this call.
4451     * <p>
4452     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4453     * guard your work against the app being relaunched.
4454     */
4455    private void killUid(int appId, int userId, String reason) {
4456        final long identity = Binder.clearCallingIdentity();
4457        try {
4458            IActivityManager am = ActivityManagerNative.getDefault();
4459            if (am != null) {
4460                try {
4461                    am.killUid(appId, userId, reason);
4462                } catch (RemoteException e) {
4463                    /* ignore - same process */
4464                }
4465            }
4466        } finally {
4467            Binder.restoreCallingIdentity(identity);
4468        }
4469    }
4470
4471    /**
4472     * Compares two sets of signatures. Returns:
4473     * <br />
4474     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4475     * <br />
4476     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4477     * <br />
4478     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4479     * <br />
4480     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4481     * <br />
4482     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4483     */
4484    static int compareSignatures(Signature[] s1, Signature[] s2) {
4485        if (s1 == null) {
4486            return s2 == null
4487                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4488                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4489        }
4490
4491        if (s2 == null) {
4492            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4493        }
4494
4495        if (s1.length != s2.length) {
4496            return PackageManager.SIGNATURE_NO_MATCH;
4497        }
4498
4499        // Since both signature sets are of size 1, we can compare without HashSets.
4500        if (s1.length == 1) {
4501            return s1[0].equals(s2[0]) ?
4502                    PackageManager.SIGNATURE_MATCH :
4503                    PackageManager.SIGNATURE_NO_MATCH;
4504        }
4505
4506        ArraySet<Signature> set1 = new ArraySet<Signature>();
4507        for (Signature sig : s1) {
4508            set1.add(sig);
4509        }
4510        ArraySet<Signature> set2 = new ArraySet<Signature>();
4511        for (Signature sig : s2) {
4512            set2.add(sig);
4513        }
4514        // Make sure s2 contains all signatures in s1.
4515        if (set1.equals(set2)) {
4516            return PackageManager.SIGNATURE_MATCH;
4517        }
4518        return PackageManager.SIGNATURE_NO_MATCH;
4519    }
4520
4521    /**
4522     * If the database version for this type of package (internal storage or
4523     * external storage) is less than the version where package signatures
4524     * were updated, return true.
4525     */
4526    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4527        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4528        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4529    }
4530
4531    /**
4532     * Used for backward compatibility to make sure any packages with
4533     * certificate chains get upgraded to the new style. {@code existingSigs}
4534     * will be in the old format (since they were stored on disk from before the
4535     * system upgrade) and {@code scannedSigs} will be in the newer format.
4536     */
4537    private int compareSignaturesCompat(PackageSignatures existingSigs,
4538            PackageParser.Package scannedPkg) {
4539        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4540            return PackageManager.SIGNATURE_NO_MATCH;
4541        }
4542
4543        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4544        for (Signature sig : existingSigs.mSignatures) {
4545            existingSet.add(sig);
4546        }
4547        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4548        for (Signature sig : scannedPkg.mSignatures) {
4549            try {
4550                Signature[] chainSignatures = sig.getChainSignatures();
4551                for (Signature chainSig : chainSignatures) {
4552                    scannedCompatSet.add(chainSig);
4553                }
4554            } catch (CertificateEncodingException e) {
4555                scannedCompatSet.add(sig);
4556            }
4557        }
4558        /*
4559         * Make sure the expanded scanned set contains all signatures in the
4560         * existing one.
4561         */
4562        if (scannedCompatSet.equals(existingSet)) {
4563            // Migrate the old signatures to the new scheme.
4564            existingSigs.assignSignatures(scannedPkg.mSignatures);
4565            // The new KeySets will be re-added later in the scanning process.
4566            synchronized (mPackages) {
4567                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4568            }
4569            return PackageManager.SIGNATURE_MATCH;
4570        }
4571        return PackageManager.SIGNATURE_NO_MATCH;
4572    }
4573
4574    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4575        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4576        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4577    }
4578
4579    private int compareSignaturesRecover(PackageSignatures existingSigs,
4580            PackageParser.Package scannedPkg) {
4581        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4582            return PackageManager.SIGNATURE_NO_MATCH;
4583        }
4584
4585        String msg = null;
4586        try {
4587            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4588                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4589                        + scannedPkg.packageName);
4590                return PackageManager.SIGNATURE_MATCH;
4591            }
4592        } catch (CertificateException e) {
4593            msg = e.getMessage();
4594        }
4595
4596        logCriticalInfo(Log.INFO,
4597                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4598        return PackageManager.SIGNATURE_NO_MATCH;
4599    }
4600
4601    @Override
4602    public List<String> getAllPackages() {
4603        synchronized (mPackages) {
4604            return new ArrayList<String>(mPackages.keySet());
4605        }
4606    }
4607
4608    @Override
4609    public String[] getPackagesForUid(int uid) {
4610        uid = UserHandle.getAppId(uid);
4611        // reader
4612        synchronized (mPackages) {
4613            Object obj = mSettings.getUserIdLPr(uid);
4614            if (obj instanceof SharedUserSetting) {
4615                final SharedUserSetting sus = (SharedUserSetting) obj;
4616                final int N = sus.packages.size();
4617                final String[] res = new String[N];
4618                for (int i = 0; i < N; i++) {
4619                    res[i] = sus.packages.valueAt(i).name;
4620                }
4621                return res;
4622            } else if (obj instanceof PackageSetting) {
4623                final PackageSetting ps = (PackageSetting) obj;
4624                return new String[] { ps.name };
4625            }
4626        }
4627        return null;
4628    }
4629
4630    @Override
4631    public String getNameForUid(int uid) {
4632        // reader
4633        synchronized (mPackages) {
4634            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4635            if (obj instanceof SharedUserSetting) {
4636                final SharedUserSetting sus = (SharedUserSetting) obj;
4637                return sus.name + ":" + sus.userId;
4638            } else if (obj instanceof PackageSetting) {
4639                final PackageSetting ps = (PackageSetting) obj;
4640                return ps.name;
4641            }
4642        }
4643        return null;
4644    }
4645
4646    @Override
4647    public int getUidForSharedUser(String sharedUserName) {
4648        if(sharedUserName == null) {
4649            return -1;
4650        }
4651        // reader
4652        synchronized (mPackages) {
4653            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4654            if (suid == null) {
4655                return -1;
4656            }
4657            return suid.userId;
4658        }
4659    }
4660
4661    @Override
4662    public int getFlagsForUid(int uid) {
4663        synchronized (mPackages) {
4664            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4665            if (obj instanceof SharedUserSetting) {
4666                final SharedUserSetting sus = (SharedUserSetting) obj;
4667                return sus.pkgFlags;
4668            } else if (obj instanceof PackageSetting) {
4669                final PackageSetting ps = (PackageSetting) obj;
4670                return ps.pkgFlags;
4671            }
4672        }
4673        return 0;
4674    }
4675
4676    @Override
4677    public int getPrivateFlagsForUid(int uid) {
4678        synchronized (mPackages) {
4679            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4680            if (obj instanceof SharedUserSetting) {
4681                final SharedUserSetting sus = (SharedUserSetting) obj;
4682                return sus.pkgPrivateFlags;
4683            } else if (obj instanceof PackageSetting) {
4684                final PackageSetting ps = (PackageSetting) obj;
4685                return ps.pkgPrivateFlags;
4686            }
4687        }
4688        return 0;
4689    }
4690
4691    @Override
4692    public boolean isUidPrivileged(int uid) {
4693        uid = UserHandle.getAppId(uid);
4694        // reader
4695        synchronized (mPackages) {
4696            Object obj = mSettings.getUserIdLPr(uid);
4697            if (obj instanceof SharedUserSetting) {
4698                final SharedUserSetting sus = (SharedUserSetting) obj;
4699                final Iterator<PackageSetting> it = sus.packages.iterator();
4700                while (it.hasNext()) {
4701                    if (it.next().isPrivileged()) {
4702                        return true;
4703                    }
4704                }
4705            } else if (obj instanceof PackageSetting) {
4706                final PackageSetting ps = (PackageSetting) obj;
4707                return ps.isPrivileged();
4708            }
4709        }
4710        return false;
4711    }
4712
4713    @Override
4714    public String[] getAppOpPermissionPackages(String permissionName) {
4715        synchronized (mPackages) {
4716            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4717            if (pkgs == null) {
4718                return null;
4719            }
4720            return pkgs.toArray(new String[pkgs.size()]);
4721        }
4722    }
4723
4724    @Override
4725    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4726            int flags, int userId) {
4727        try {
4728            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4729
4730            if (!sUserManager.exists(userId)) return null;
4731            flags = updateFlagsForResolve(flags, userId, intent);
4732            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4733                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4734
4735            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4736            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4737                    flags, userId);
4738            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4739
4740            final ResolveInfo bestChoice =
4741                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4742
4743            if (isEphemeralAllowed(intent, query, userId)) {
4744                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4745                final EphemeralResolveInfo ai =
4746                        getEphemeralResolveInfo(intent, resolvedType, userId);
4747                if (ai != null) {
4748                    if (DEBUG_EPHEMERAL) {
4749                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4750                    }
4751                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4752                    bestChoice.ephemeralResolveInfo = ai;
4753                }
4754                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4755            }
4756            return bestChoice;
4757        } finally {
4758            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4759        }
4760    }
4761
4762    @Override
4763    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4764            IntentFilter filter, int match, ComponentName activity) {
4765        final int userId = UserHandle.getCallingUserId();
4766        if (DEBUG_PREFERRED) {
4767            Log.v(TAG, "setLastChosenActivity intent=" + intent
4768                + " resolvedType=" + resolvedType
4769                + " flags=" + flags
4770                + " filter=" + filter
4771                + " match=" + match
4772                + " activity=" + activity);
4773            filter.dump(new PrintStreamPrinter(System.out), "    ");
4774        }
4775        intent.setComponent(null);
4776        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4777                userId);
4778        // Find any earlier preferred or last chosen entries and nuke them
4779        findPreferredActivity(intent, resolvedType,
4780                flags, query, 0, false, true, false, userId);
4781        // Add the new activity as the last chosen for this filter
4782        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4783                "Setting last chosen");
4784    }
4785
4786    @Override
4787    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4788        final int userId = UserHandle.getCallingUserId();
4789        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4790        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4791                userId);
4792        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4793                false, false, false, userId);
4794    }
4795
4796
4797    private boolean isEphemeralAllowed(
4798            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4799        // Short circuit and return early if possible.
4800        if (DISABLE_EPHEMERAL_APPS) {
4801            return false;
4802        }
4803        final int callingUser = UserHandle.getCallingUserId();
4804        if (callingUser != UserHandle.USER_SYSTEM) {
4805            return false;
4806        }
4807        if (mEphemeralResolverConnection == null) {
4808            return false;
4809        }
4810        if (intent.getComponent() != null) {
4811            return false;
4812        }
4813        if (intent.getPackage() != null) {
4814            return false;
4815        }
4816        final boolean isWebUri = hasWebURI(intent);
4817        if (!isWebUri) {
4818            return false;
4819        }
4820        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4821        synchronized (mPackages) {
4822            final int count = resolvedActivites.size();
4823            for (int n = 0; n < count; n++) {
4824                ResolveInfo info = resolvedActivites.get(n);
4825                String packageName = info.activityInfo.packageName;
4826                PackageSetting ps = mSettings.mPackages.get(packageName);
4827                if (ps != null) {
4828                    // Try to get the status from User settings first
4829                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4830                    int status = (int) (packedStatus >> 32);
4831                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4832                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4833                        if (DEBUG_EPHEMERAL) {
4834                            Slog.v(TAG, "DENY ephemeral apps;"
4835                                + " pkg: " + packageName + ", status: " + status);
4836                        }
4837                        return false;
4838                    }
4839                }
4840            }
4841        }
4842        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4843        return true;
4844    }
4845
4846    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4847            int userId) {
4848        final int ephemeralPrefixMask = Global.getInt(mContext.getContentResolver(),
4849                Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK);
4850        final int ephemeralPrefixCount = Global.getInt(mContext.getContentResolver(),
4851                Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT);
4852        final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask,
4853                ephemeralPrefixCount);
4854        final int[] shaPrefix = digest.getDigestPrefix();
4855        final byte[][] digestBytes = digest.getDigestBytes();
4856        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4857                mEphemeralResolverConnection.getEphemeralResolveInfoList(
4858                        shaPrefix, ephemeralPrefixMask);
4859        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4860            // No hash prefix match; there are no ephemeral apps for this domain.
4861            return null;
4862        }
4863
4864        // Go in reverse order so we match the narrowest scope first.
4865        for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
4866            for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) {
4867                if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) {
4868                    continue;
4869                }
4870                final List<IntentFilter> filters = ephemeralApplication.getFilters();
4871                // No filters; this should never happen.
4872                if (filters.isEmpty()) {
4873                    continue;
4874                }
4875                // We have a domain match; resolve the filters to see if anything matches.
4876                final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4877                for (int j = filters.size() - 1; j >= 0; --j) {
4878                    final EphemeralResolveIntentInfo intentInfo =
4879                            new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4880                    ephemeralResolver.addFilter(intentInfo);
4881                }
4882                List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4883                        intent, resolvedType, false /*defaultOnly*/, userId);
4884                if (!matchedResolveInfoList.isEmpty()) {
4885                    return matchedResolveInfoList.get(0);
4886                }
4887            }
4888        }
4889        // Hash or filter mis-match; no ephemeral apps for this domain.
4890        return null;
4891    }
4892
4893    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4894            int flags, List<ResolveInfo> query, int userId) {
4895        if (query != null) {
4896            final int N = query.size();
4897            if (N == 1) {
4898                return query.get(0);
4899            } else if (N > 1) {
4900                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4901                // If there is more than one activity with the same priority,
4902                // then let the user decide between them.
4903                ResolveInfo r0 = query.get(0);
4904                ResolveInfo r1 = query.get(1);
4905                if (DEBUG_INTENT_MATCHING || debug) {
4906                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4907                            + r1.activityInfo.name + "=" + r1.priority);
4908                }
4909                // If the first activity has a higher priority, or a different
4910                // default, then it is always desirable to pick it.
4911                if (r0.priority != r1.priority
4912                        || r0.preferredOrder != r1.preferredOrder
4913                        || r0.isDefault != r1.isDefault) {
4914                    return query.get(0);
4915                }
4916                // If we have saved a preference for a preferred activity for
4917                // this Intent, use that.
4918                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4919                        flags, query, r0.priority, true, false, debug, userId);
4920                if (ri != null) {
4921                    return ri;
4922                }
4923                ri = new ResolveInfo(mResolveInfo);
4924                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4925                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
4926                // If all of the options come from the same package, show the application's
4927                // label and icon instead of the generic resolver's.
4928                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
4929                // and then throw away the ResolveInfo itself, meaning that the caller loses
4930                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
4931                // a fallback for this case; we only set the target package's resources on
4932                // the ResolveInfo, not the ActivityInfo.
4933                final String intentPackage = intent.getPackage();
4934                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
4935                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
4936                    ri.resolvePackageName = intentPackage;
4937                    if (userNeedsBadging(userId)) {
4938                        ri.noResourceId = true;
4939                    } else {
4940                        ri.icon = appi.icon;
4941                    }
4942                    ri.iconResourceId = appi.icon;
4943                    ri.labelRes = appi.labelRes;
4944                }
4945                ri.activityInfo.applicationInfo = new ApplicationInfo(
4946                        ri.activityInfo.applicationInfo);
4947                if (userId != 0) {
4948                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4949                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4950                }
4951                // Make sure that the resolver is displayable in car mode
4952                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4953                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4954                return ri;
4955            }
4956        }
4957        return null;
4958    }
4959
4960    /**
4961     * Return true if the given list is not empty and all of its contents have
4962     * an activityInfo with the given package name.
4963     */
4964    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
4965        if (ArrayUtils.isEmpty(list)) {
4966            return false;
4967        }
4968        for (int i = 0, N = list.size(); i < N; i++) {
4969            final ResolveInfo ri = list.get(i);
4970            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
4971            if (ai == null || !packageName.equals(ai.packageName)) {
4972                return false;
4973            }
4974        }
4975        return true;
4976    }
4977
4978    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4979            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4980        final int N = query.size();
4981        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4982                .get(userId);
4983        // Get the list of persistent preferred activities that handle the intent
4984        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4985        List<PersistentPreferredActivity> pprefs = ppir != null
4986                ? ppir.queryIntent(intent, resolvedType,
4987                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4988                : null;
4989        if (pprefs != null && pprefs.size() > 0) {
4990            final int M = pprefs.size();
4991            for (int i=0; i<M; i++) {
4992                final PersistentPreferredActivity ppa = pprefs.get(i);
4993                if (DEBUG_PREFERRED || debug) {
4994                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4995                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4996                            + "\n  component=" + ppa.mComponent);
4997                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4998                }
4999                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5000                        flags | MATCH_DISABLED_COMPONENTS, userId);
5001                if (DEBUG_PREFERRED || debug) {
5002                    Slog.v(TAG, "Found persistent preferred activity:");
5003                    if (ai != null) {
5004                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5005                    } else {
5006                        Slog.v(TAG, "  null");
5007                    }
5008                }
5009                if (ai == null) {
5010                    // This previously registered persistent preferred activity
5011                    // component is no longer known. Ignore it and do NOT remove it.
5012                    continue;
5013                }
5014                for (int j=0; j<N; j++) {
5015                    final ResolveInfo ri = query.get(j);
5016                    if (!ri.activityInfo.applicationInfo.packageName
5017                            .equals(ai.applicationInfo.packageName)) {
5018                        continue;
5019                    }
5020                    if (!ri.activityInfo.name.equals(ai.name)) {
5021                        continue;
5022                    }
5023                    //  Found a persistent preference that can handle the intent.
5024                    if (DEBUG_PREFERRED || debug) {
5025                        Slog.v(TAG, "Returning persistent preferred activity: " +
5026                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5027                    }
5028                    return ri;
5029                }
5030            }
5031        }
5032        return null;
5033    }
5034
5035    // TODO: handle preferred activities missing while user has amnesia
5036    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5037            List<ResolveInfo> query, int priority, boolean always,
5038            boolean removeMatches, boolean debug, int userId) {
5039        if (!sUserManager.exists(userId)) return null;
5040        flags = updateFlagsForResolve(flags, userId, intent);
5041        // writer
5042        synchronized (mPackages) {
5043            if (intent.getSelector() != null) {
5044                intent = intent.getSelector();
5045            }
5046            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5047
5048            // Try to find a matching persistent preferred activity.
5049            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5050                    debug, userId);
5051
5052            // If a persistent preferred activity matched, use it.
5053            if (pri != null) {
5054                return pri;
5055            }
5056
5057            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5058            // Get the list of preferred activities that handle the intent
5059            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5060            List<PreferredActivity> prefs = pir != null
5061                    ? pir.queryIntent(intent, resolvedType,
5062                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5063                    : null;
5064            if (prefs != null && prefs.size() > 0) {
5065                boolean changed = false;
5066                try {
5067                    // First figure out how good the original match set is.
5068                    // We will only allow preferred activities that came
5069                    // from the same match quality.
5070                    int match = 0;
5071
5072                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5073
5074                    final int N = query.size();
5075                    for (int j=0; j<N; j++) {
5076                        final ResolveInfo ri = query.get(j);
5077                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5078                                + ": 0x" + Integer.toHexString(match));
5079                        if (ri.match > match) {
5080                            match = ri.match;
5081                        }
5082                    }
5083
5084                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5085                            + Integer.toHexString(match));
5086
5087                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5088                    final int M = prefs.size();
5089                    for (int i=0; i<M; i++) {
5090                        final PreferredActivity pa = prefs.get(i);
5091                        if (DEBUG_PREFERRED || debug) {
5092                            Slog.v(TAG, "Checking PreferredActivity ds="
5093                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5094                                    + "\n  component=" + pa.mPref.mComponent);
5095                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5096                        }
5097                        if (pa.mPref.mMatch != match) {
5098                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5099                                    + Integer.toHexString(pa.mPref.mMatch));
5100                            continue;
5101                        }
5102                        // If it's not an "always" type preferred activity and that's what we're
5103                        // looking for, skip it.
5104                        if (always && !pa.mPref.mAlways) {
5105                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5106                            continue;
5107                        }
5108                        final ActivityInfo ai = getActivityInfo(
5109                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5110                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5111                                userId);
5112                        if (DEBUG_PREFERRED || debug) {
5113                            Slog.v(TAG, "Found preferred activity:");
5114                            if (ai != null) {
5115                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5116                            } else {
5117                                Slog.v(TAG, "  null");
5118                            }
5119                        }
5120                        if (ai == null) {
5121                            // This previously registered preferred activity
5122                            // component is no longer known.  Most likely an update
5123                            // to the app was installed and in the new version this
5124                            // component no longer exists.  Clean it up by removing
5125                            // it from the preferred activities list, and skip it.
5126                            Slog.w(TAG, "Removing dangling preferred activity: "
5127                                    + pa.mPref.mComponent);
5128                            pir.removeFilter(pa);
5129                            changed = true;
5130                            continue;
5131                        }
5132                        for (int j=0; j<N; j++) {
5133                            final ResolveInfo ri = query.get(j);
5134                            if (!ri.activityInfo.applicationInfo.packageName
5135                                    .equals(ai.applicationInfo.packageName)) {
5136                                continue;
5137                            }
5138                            if (!ri.activityInfo.name.equals(ai.name)) {
5139                                continue;
5140                            }
5141
5142                            if (removeMatches) {
5143                                pir.removeFilter(pa);
5144                                changed = true;
5145                                if (DEBUG_PREFERRED) {
5146                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5147                                }
5148                                break;
5149                            }
5150
5151                            // Okay we found a previously set preferred or last chosen app.
5152                            // If the result set is different from when this
5153                            // was created, we need to clear it and re-ask the
5154                            // user their preference, if we're looking for an "always" type entry.
5155                            if (always && !pa.mPref.sameSet(query)) {
5156                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5157                                        + intent + " type " + resolvedType);
5158                                if (DEBUG_PREFERRED) {
5159                                    Slog.v(TAG, "Removing preferred activity since set changed "
5160                                            + pa.mPref.mComponent);
5161                                }
5162                                pir.removeFilter(pa);
5163                                // Re-add the filter as a "last chosen" entry (!always)
5164                                PreferredActivity lastChosen = new PreferredActivity(
5165                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5166                                pir.addFilter(lastChosen);
5167                                changed = true;
5168                                return null;
5169                            }
5170
5171                            // Yay! Either the set matched or we're looking for the last chosen
5172                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5173                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5174                            return ri;
5175                        }
5176                    }
5177                } finally {
5178                    if (changed) {
5179                        if (DEBUG_PREFERRED) {
5180                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5181                        }
5182                        scheduleWritePackageRestrictionsLocked(userId);
5183                    }
5184                }
5185            }
5186        }
5187        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5188        return null;
5189    }
5190
5191    /*
5192     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5193     */
5194    @Override
5195    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5196            int targetUserId) {
5197        mContext.enforceCallingOrSelfPermission(
5198                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5199        List<CrossProfileIntentFilter> matches =
5200                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5201        if (matches != null) {
5202            int size = matches.size();
5203            for (int i = 0; i < size; i++) {
5204                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5205            }
5206        }
5207        if (hasWebURI(intent)) {
5208            // cross-profile app linking works only towards the parent.
5209            final UserInfo parent = getProfileParent(sourceUserId);
5210            synchronized(mPackages) {
5211                int flags = updateFlagsForResolve(0, parent.id, intent);
5212                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5213                        intent, resolvedType, flags, sourceUserId, parent.id);
5214                return xpDomainInfo != null;
5215            }
5216        }
5217        return false;
5218    }
5219
5220    private UserInfo getProfileParent(int userId) {
5221        final long identity = Binder.clearCallingIdentity();
5222        try {
5223            return sUserManager.getProfileParent(userId);
5224        } finally {
5225            Binder.restoreCallingIdentity(identity);
5226        }
5227    }
5228
5229    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5230            String resolvedType, int userId) {
5231        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5232        if (resolver != null) {
5233            return resolver.queryIntent(intent, resolvedType, false, userId);
5234        }
5235        return null;
5236    }
5237
5238    @Override
5239    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5240            String resolvedType, int flags, int userId) {
5241        try {
5242            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5243
5244            return new ParceledListSlice<>(
5245                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5246        } finally {
5247            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5248        }
5249    }
5250
5251    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5252            String resolvedType, int flags, int userId) {
5253        if (!sUserManager.exists(userId)) return Collections.emptyList();
5254        flags = updateFlagsForResolve(flags, userId, intent);
5255        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5256                false /* requireFullPermission */, false /* checkShell */,
5257                "query intent activities");
5258        ComponentName comp = intent.getComponent();
5259        if (comp == null) {
5260            if (intent.getSelector() != null) {
5261                intent = intent.getSelector();
5262                comp = intent.getComponent();
5263            }
5264        }
5265
5266        if (comp != null) {
5267            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5268            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5269            if (ai != null) {
5270                final ResolveInfo ri = new ResolveInfo();
5271                ri.activityInfo = ai;
5272                list.add(ri);
5273            }
5274            return list;
5275        }
5276
5277        // reader
5278        synchronized (mPackages) {
5279            final String pkgName = intent.getPackage();
5280            if (pkgName == null) {
5281                List<CrossProfileIntentFilter> matchingFilters =
5282                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5283                // Check for results that need to skip the current profile.
5284                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5285                        resolvedType, flags, userId);
5286                if (xpResolveInfo != null) {
5287                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5288                    result.add(xpResolveInfo);
5289                    return filterIfNotSystemUser(result, userId);
5290                }
5291
5292                // Check for results in the current profile.
5293                List<ResolveInfo> result = mActivities.queryIntent(
5294                        intent, resolvedType, flags, userId);
5295                result = filterIfNotSystemUser(result, userId);
5296
5297                // Check for cross profile results.
5298                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5299                xpResolveInfo = queryCrossProfileIntents(
5300                        matchingFilters, intent, resolvedType, flags, userId,
5301                        hasNonNegativePriorityResult);
5302                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5303                    boolean isVisibleToUser = filterIfNotSystemUser(
5304                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5305                    if (isVisibleToUser) {
5306                        result.add(xpResolveInfo);
5307                        Collections.sort(result, mResolvePrioritySorter);
5308                    }
5309                }
5310                if (hasWebURI(intent)) {
5311                    CrossProfileDomainInfo xpDomainInfo = null;
5312                    final UserInfo parent = getProfileParent(userId);
5313                    if (parent != null) {
5314                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5315                                flags, userId, parent.id);
5316                    }
5317                    if (xpDomainInfo != null) {
5318                        if (xpResolveInfo != null) {
5319                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5320                            // in the result.
5321                            result.remove(xpResolveInfo);
5322                        }
5323                        if (result.size() == 0) {
5324                            result.add(xpDomainInfo.resolveInfo);
5325                            return result;
5326                        }
5327                    } else if (result.size() <= 1) {
5328                        return result;
5329                    }
5330                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5331                            xpDomainInfo, userId);
5332                    Collections.sort(result, mResolvePrioritySorter);
5333                }
5334                return result;
5335            }
5336            final PackageParser.Package pkg = mPackages.get(pkgName);
5337            if (pkg != null) {
5338                return filterIfNotSystemUser(
5339                        mActivities.queryIntentForPackage(
5340                                intent, resolvedType, flags, pkg.activities, userId),
5341                        userId);
5342            }
5343            return new ArrayList<ResolveInfo>();
5344        }
5345    }
5346
5347    private static class CrossProfileDomainInfo {
5348        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5349        ResolveInfo resolveInfo;
5350        /* Best domain verification status of the activities found in the other profile */
5351        int bestDomainVerificationStatus;
5352    }
5353
5354    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5355            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5356        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5357                sourceUserId)) {
5358            return null;
5359        }
5360        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5361                resolvedType, flags, parentUserId);
5362
5363        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5364            return null;
5365        }
5366        CrossProfileDomainInfo result = null;
5367        int size = resultTargetUser.size();
5368        for (int i = 0; i < size; i++) {
5369            ResolveInfo riTargetUser = resultTargetUser.get(i);
5370            // Intent filter verification is only for filters that specify a host. So don't return
5371            // those that handle all web uris.
5372            if (riTargetUser.handleAllWebDataURI) {
5373                continue;
5374            }
5375            String packageName = riTargetUser.activityInfo.packageName;
5376            PackageSetting ps = mSettings.mPackages.get(packageName);
5377            if (ps == null) {
5378                continue;
5379            }
5380            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5381            int status = (int)(verificationState >> 32);
5382            if (result == null) {
5383                result = new CrossProfileDomainInfo();
5384                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5385                        sourceUserId, parentUserId);
5386                result.bestDomainVerificationStatus = status;
5387            } else {
5388                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5389                        result.bestDomainVerificationStatus);
5390            }
5391        }
5392        // Don't consider matches with status NEVER across profiles.
5393        if (result != null && result.bestDomainVerificationStatus
5394                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5395            return null;
5396        }
5397        return result;
5398    }
5399
5400    /**
5401     * Verification statuses are ordered from the worse to the best, except for
5402     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5403     */
5404    private int bestDomainVerificationStatus(int status1, int status2) {
5405        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5406            return status2;
5407        }
5408        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5409            return status1;
5410        }
5411        return (int) MathUtils.max(status1, status2);
5412    }
5413
5414    private boolean isUserEnabled(int userId) {
5415        long callingId = Binder.clearCallingIdentity();
5416        try {
5417            UserInfo userInfo = sUserManager.getUserInfo(userId);
5418            return userInfo != null && userInfo.isEnabled();
5419        } finally {
5420            Binder.restoreCallingIdentity(callingId);
5421        }
5422    }
5423
5424    /**
5425     * Filter out activities with systemUserOnly flag set, when current user is not System.
5426     *
5427     * @return filtered list
5428     */
5429    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5430        if (userId == UserHandle.USER_SYSTEM) {
5431            return resolveInfos;
5432        }
5433        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5434            ResolveInfo info = resolveInfos.get(i);
5435            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5436                resolveInfos.remove(i);
5437            }
5438        }
5439        return resolveInfos;
5440    }
5441
5442    /**
5443     * @param resolveInfos list of resolve infos in descending priority order
5444     * @return if the list contains a resolve info with non-negative priority
5445     */
5446    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5447        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5448    }
5449
5450    private static boolean hasWebURI(Intent intent) {
5451        if (intent.getData() == null) {
5452            return false;
5453        }
5454        final String scheme = intent.getScheme();
5455        if (TextUtils.isEmpty(scheme)) {
5456            return false;
5457        }
5458        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5459    }
5460
5461    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5462            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5463            int userId) {
5464        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5465
5466        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5467            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5468                    candidates.size());
5469        }
5470
5471        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5472        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5473        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5474        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5475        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5476        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5477
5478        synchronized (mPackages) {
5479            final int count = candidates.size();
5480            // First, try to use linked apps. Partition the candidates into four lists:
5481            // one for the final results, one for the "do not use ever", one for "undefined status"
5482            // and finally one for "browser app type".
5483            for (int n=0; n<count; n++) {
5484                ResolveInfo info = candidates.get(n);
5485                String packageName = info.activityInfo.packageName;
5486                PackageSetting ps = mSettings.mPackages.get(packageName);
5487                if (ps != null) {
5488                    // Add to the special match all list (Browser use case)
5489                    if (info.handleAllWebDataURI) {
5490                        matchAllList.add(info);
5491                        continue;
5492                    }
5493                    // Try to get the status from User settings first
5494                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5495                    int status = (int)(packedStatus >> 32);
5496                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5497                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5498                        if (DEBUG_DOMAIN_VERIFICATION) {
5499                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5500                                    + " : linkgen=" + linkGeneration);
5501                        }
5502                        // Use link-enabled generation as preferredOrder, i.e.
5503                        // prefer newly-enabled over earlier-enabled.
5504                        info.preferredOrder = linkGeneration;
5505                        alwaysList.add(info);
5506                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5507                        if (DEBUG_DOMAIN_VERIFICATION) {
5508                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5509                        }
5510                        neverList.add(info);
5511                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5512                        if (DEBUG_DOMAIN_VERIFICATION) {
5513                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5514                        }
5515                        alwaysAskList.add(info);
5516                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5517                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5518                        if (DEBUG_DOMAIN_VERIFICATION) {
5519                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5520                        }
5521                        undefinedList.add(info);
5522                    }
5523                }
5524            }
5525
5526            // We'll want to include browser possibilities in a few cases
5527            boolean includeBrowser = false;
5528
5529            // First try to add the "always" resolution(s) for the current user, if any
5530            if (alwaysList.size() > 0) {
5531                result.addAll(alwaysList);
5532            } else {
5533                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5534                result.addAll(undefinedList);
5535                // Maybe add one for the other profile.
5536                if (xpDomainInfo != null && (
5537                        xpDomainInfo.bestDomainVerificationStatus
5538                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5539                    result.add(xpDomainInfo.resolveInfo);
5540                }
5541                includeBrowser = true;
5542            }
5543
5544            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5545            // If there were 'always' entries their preferred order has been set, so we also
5546            // back that off to make the alternatives equivalent
5547            if (alwaysAskList.size() > 0) {
5548                for (ResolveInfo i : result) {
5549                    i.preferredOrder = 0;
5550                }
5551                result.addAll(alwaysAskList);
5552                includeBrowser = true;
5553            }
5554
5555            if (includeBrowser) {
5556                // Also add browsers (all of them or only the default one)
5557                if (DEBUG_DOMAIN_VERIFICATION) {
5558                    Slog.v(TAG, "   ...including browsers in candidate set");
5559                }
5560                if ((matchFlags & MATCH_ALL) != 0) {
5561                    result.addAll(matchAllList);
5562                } else {
5563                    // Browser/generic handling case.  If there's a default browser, go straight
5564                    // to that (but only if there is no other higher-priority match).
5565                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5566                    int maxMatchPrio = 0;
5567                    ResolveInfo defaultBrowserMatch = null;
5568                    final int numCandidates = matchAllList.size();
5569                    for (int n = 0; n < numCandidates; n++) {
5570                        ResolveInfo info = matchAllList.get(n);
5571                        // track the highest overall match priority...
5572                        if (info.priority > maxMatchPrio) {
5573                            maxMatchPrio = info.priority;
5574                        }
5575                        // ...and the highest-priority default browser match
5576                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5577                            if (defaultBrowserMatch == null
5578                                    || (defaultBrowserMatch.priority < info.priority)) {
5579                                if (debug) {
5580                                    Slog.v(TAG, "Considering default browser match " + info);
5581                                }
5582                                defaultBrowserMatch = info;
5583                            }
5584                        }
5585                    }
5586                    if (defaultBrowserMatch != null
5587                            && defaultBrowserMatch.priority >= maxMatchPrio
5588                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5589                    {
5590                        if (debug) {
5591                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5592                        }
5593                        result.add(defaultBrowserMatch);
5594                    } else {
5595                        result.addAll(matchAllList);
5596                    }
5597                }
5598
5599                // If there is nothing selected, add all candidates and remove the ones that the user
5600                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5601                if (result.size() == 0) {
5602                    result.addAll(candidates);
5603                    result.removeAll(neverList);
5604                }
5605            }
5606        }
5607        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5608            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5609                    result.size());
5610            for (ResolveInfo info : result) {
5611                Slog.v(TAG, "  + " + info.activityInfo);
5612            }
5613        }
5614        return result;
5615    }
5616
5617    // Returns a packed value as a long:
5618    //
5619    // high 'int'-sized word: link status: undefined/ask/never/always.
5620    // low 'int'-sized word: relative priority among 'always' results.
5621    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5622        long result = ps.getDomainVerificationStatusForUser(userId);
5623        // if none available, get the master status
5624        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5625            if (ps.getIntentFilterVerificationInfo() != null) {
5626                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5627            }
5628        }
5629        return result;
5630    }
5631
5632    private ResolveInfo querySkipCurrentProfileIntents(
5633            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5634            int flags, int sourceUserId) {
5635        if (matchingFilters != null) {
5636            int size = matchingFilters.size();
5637            for (int i = 0; i < size; i ++) {
5638                CrossProfileIntentFilter filter = matchingFilters.get(i);
5639                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5640                    // Checking if there are activities in the target user that can handle the
5641                    // intent.
5642                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5643                            resolvedType, flags, sourceUserId);
5644                    if (resolveInfo != null) {
5645                        return resolveInfo;
5646                    }
5647                }
5648            }
5649        }
5650        return null;
5651    }
5652
5653    // Return matching ResolveInfo in target user if any.
5654    private ResolveInfo queryCrossProfileIntents(
5655            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5656            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5657        if (matchingFilters != null) {
5658            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5659            // match the same intent. For performance reasons, it is better not to
5660            // run queryIntent twice for the same userId
5661            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5662            int size = matchingFilters.size();
5663            for (int i = 0; i < size; i++) {
5664                CrossProfileIntentFilter filter = matchingFilters.get(i);
5665                int targetUserId = filter.getTargetUserId();
5666                boolean skipCurrentProfile =
5667                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5668                boolean skipCurrentProfileIfNoMatchFound =
5669                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5670                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5671                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5672                    // Checking if there are activities in the target user that can handle the
5673                    // intent.
5674                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5675                            resolvedType, flags, sourceUserId);
5676                    if (resolveInfo != null) return resolveInfo;
5677                    alreadyTriedUserIds.put(targetUserId, true);
5678                }
5679            }
5680        }
5681        return null;
5682    }
5683
5684    /**
5685     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5686     * will forward the intent to the filter's target user.
5687     * Otherwise, returns null.
5688     */
5689    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5690            String resolvedType, int flags, int sourceUserId) {
5691        int targetUserId = filter.getTargetUserId();
5692        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5693                resolvedType, flags, targetUserId);
5694        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5695            // If all the matches in the target profile are suspended, return null.
5696            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5697                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5698                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5699                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5700                            targetUserId);
5701                }
5702            }
5703        }
5704        return null;
5705    }
5706
5707    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5708            int sourceUserId, int targetUserId) {
5709        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5710        long ident = Binder.clearCallingIdentity();
5711        boolean targetIsProfile;
5712        try {
5713            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5714        } finally {
5715            Binder.restoreCallingIdentity(ident);
5716        }
5717        String className;
5718        if (targetIsProfile) {
5719            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5720        } else {
5721            className = FORWARD_INTENT_TO_PARENT;
5722        }
5723        ComponentName forwardingActivityComponentName = new ComponentName(
5724                mAndroidApplication.packageName, className);
5725        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5726                sourceUserId);
5727        if (!targetIsProfile) {
5728            forwardingActivityInfo.showUserIcon = targetUserId;
5729            forwardingResolveInfo.noResourceId = true;
5730        }
5731        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5732        forwardingResolveInfo.priority = 0;
5733        forwardingResolveInfo.preferredOrder = 0;
5734        forwardingResolveInfo.match = 0;
5735        forwardingResolveInfo.isDefault = true;
5736        forwardingResolveInfo.filter = filter;
5737        forwardingResolveInfo.targetUserId = targetUserId;
5738        return forwardingResolveInfo;
5739    }
5740
5741    @Override
5742    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5743            Intent[] specifics, String[] specificTypes, Intent intent,
5744            String resolvedType, int flags, int userId) {
5745        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5746                specificTypes, intent, resolvedType, flags, userId));
5747    }
5748
5749    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5750            Intent[] specifics, String[] specificTypes, Intent intent,
5751            String resolvedType, int flags, int userId) {
5752        if (!sUserManager.exists(userId)) return Collections.emptyList();
5753        flags = updateFlagsForResolve(flags, userId, intent);
5754        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5755                false /* requireFullPermission */, false /* checkShell */,
5756                "query intent activity options");
5757        final String resultsAction = intent.getAction();
5758
5759        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5760                | PackageManager.GET_RESOLVED_FILTER, userId);
5761
5762        if (DEBUG_INTENT_MATCHING) {
5763            Log.v(TAG, "Query " + intent + ": " + results);
5764        }
5765
5766        int specificsPos = 0;
5767        int N;
5768
5769        // todo: note that the algorithm used here is O(N^2).  This
5770        // isn't a problem in our current environment, but if we start running
5771        // into situations where we have more than 5 or 10 matches then this
5772        // should probably be changed to something smarter...
5773
5774        // First we go through and resolve each of the specific items
5775        // that were supplied, taking care of removing any corresponding
5776        // duplicate items in the generic resolve list.
5777        if (specifics != null) {
5778            for (int i=0; i<specifics.length; i++) {
5779                final Intent sintent = specifics[i];
5780                if (sintent == null) {
5781                    continue;
5782                }
5783
5784                if (DEBUG_INTENT_MATCHING) {
5785                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5786                }
5787
5788                String action = sintent.getAction();
5789                if (resultsAction != null && resultsAction.equals(action)) {
5790                    // If this action was explicitly requested, then don't
5791                    // remove things that have it.
5792                    action = null;
5793                }
5794
5795                ResolveInfo ri = null;
5796                ActivityInfo ai = null;
5797
5798                ComponentName comp = sintent.getComponent();
5799                if (comp == null) {
5800                    ri = resolveIntent(
5801                        sintent,
5802                        specificTypes != null ? specificTypes[i] : null,
5803                            flags, userId);
5804                    if (ri == null) {
5805                        continue;
5806                    }
5807                    if (ri == mResolveInfo) {
5808                        // ACK!  Must do something better with this.
5809                    }
5810                    ai = ri.activityInfo;
5811                    comp = new ComponentName(ai.applicationInfo.packageName,
5812                            ai.name);
5813                } else {
5814                    ai = getActivityInfo(comp, flags, userId);
5815                    if (ai == null) {
5816                        continue;
5817                    }
5818                }
5819
5820                // Look for any generic query activities that are duplicates
5821                // of this specific one, and remove them from the results.
5822                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5823                N = results.size();
5824                int j;
5825                for (j=specificsPos; j<N; j++) {
5826                    ResolveInfo sri = results.get(j);
5827                    if ((sri.activityInfo.name.equals(comp.getClassName())
5828                            && sri.activityInfo.applicationInfo.packageName.equals(
5829                                    comp.getPackageName()))
5830                        || (action != null && sri.filter.matchAction(action))) {
5831                        results.remove(j);
5832                        if (DEBUG_INTENT_MATCHING) Log.v(
5833                            TAG, "Removing duplicate item from " + j
5834                            + " due to specific " + specificsPos);
5835                        if (ri == null) {
5836                            ri = sri;
5837                        }
5838                        j--;
5839                        N--;
5840                    }
5841                }
5842
5843                // Add this specific item to its proper place.
5844                if (ri == null) {
5845                    ri = new ResolveInfo();
5846                    ri.activityInfo = ai;
5847                }
5848                results.add(specificsPos, ri);
5849                ri.specificIndex = i;
5850                specificsPos++;
5851            }
5852        }
5853
5854        // Now we go through the remaining generic results and remove any
5855        // duplicate actions that are found here.
5856        N = results.size();
5857        for (int i=specificsPos; i<N-1; i++) {
5858            final ResolveInfo rii = results.get(i);
5859            if (rii.filter == null) {
5860                continue;
5861            }
5862
5863            // Iterate over all of the actions of this result's intent
5864            // filter...  typically this should be just one.
5865            final Iterator<String> it = rii.filter.actionsIterator();
5866            if (it == null) {
5867                continue;
5868            }
5869            while (it.hasNext()) {
5870                final String action = it.next();
5871                if (resultsAction != null && resultsAction.equals(action)) {
5872                    // If this action was explicitly requested, then don't
5873                    // remove things that have it.
5874                    continue;
5875                }
5876                for (int j=i+1; j<N; j++) {
5877                    final ResolveInfo rij = results.get(j);
5878                    if (rij.filter != null && rij.filter.hasAction(action)) {
5879                        results.remove(j);
5880                        if (DEBUG_INTENT_MATCHING) Log.v(
5881                            TAG, "Removing duplicate item from " + j
5882                            + " due to action " + action + " at " + i);
5883                        j--;
5884                        N--;
5885                    }
5886                }
5887            }
5888
5889            // If the caller didn't request filter information, drop it now
5890            // so we don't have to marshall/unmarshall it.
5891            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5892                rii.filter = null;
5893            }
5894        }
5895
5896        // Filter out the caller activity if so requested.
5897        if (caller != null) {
5898            N = results.size();
5899            for (int i=0; i<N; i++) {
5900                ActivityInfo ainfo = results.get(i).activityInfo;
5901                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5902                        && caller.getClassName().equals(ainfo.name)) {
5903                    results.remove(i);
5904                    break;
5905                }
5906            }
5907        }
5908
5909        // If the caller didn't request filter information,
5910        // drop them now so we don't have to
5911        // marshall/unmarshall it.
5912        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5913            N = results.size();
5914            for (int i=0; i<N; i++) {
5915                results.get(i).filter = null;
5916            }
5917        }
5918
5919        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5920        return results;
5921    }
5922
5923    @Override
5924    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5925            String resolvedType, int flags, int userId) {
5926        return new ParceledListSlice<>(
5927                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5928    }
5929
5930    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5931            String resolvedType, int flags, int userId) {
5932        if (!sUserManager.exists(userId)) return Collections.emptyList();
5933        flags = updateFlagsForResolve(flags, userId, intent);
5934        ComponentName comp = intent.getComponent();
5935        if (comp == null) {
5936            if (intent.getSelector() != null) {
5937                intent = intent.getSelector();
5938                comp = intent.getComponent();
5939            }
5940        }
5941        if (comp != null) {
5942            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5943            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5944            if (ai != null) {
5945                ResolveInfo ri = new ResolveInfo();
5946                ri.activityInfo = ai;
5947                list.add(ri);
5948            }
5949            return list;
5950        }
5951
5952        // reader
5953        synchronized (mPackages) {
5954            String pkgName = intent.getPackage();
5955            if (pkgName == null) {
5956                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5957            }
5958            final PackageParser.Package pkg = mPackages.get(pkgName);
5959            if (pkg != null) {
5960                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5961                        userId);
5962            }
5963            return Collections.emptyList();
5964        }
5965    }
5966
5967    @Override
5968    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5969        if (!sUserManager.exists(userId)) return null;
5970        flags = updateFlagsForResolve(flags, userId, intent);
5971        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
5972        if (query != null) {
5973            if (query.size() >= 1) {
5974                // If there is more than one service with the same priority,
5975                // just arbitrarily pick the first one.
5976                return query.get(0);
5977            }
5978        }
5979        return null;
5980    }
5981
5982    @Override
5983    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
5984            String resolvedType, int flags, int userId) {
5985        return new ParceledListSlice<>(
5986                queryIntentServicesInternal(intent, resolvedType, flags, userId));
5987    }
5988
5989    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
5990            String resolvedType, int flags, int userId) {
5991        if (!sUserManager.exists(userId)) return Collections.emptyList();
5992        flags = updateFlagsForResolve(flags, userId, intent);
5993        ComponentName comp = intent.getComponent();
5994        if (comp == null) {
5995            if (intent.getSelector() != null) {
5996                intent = intent.getSelector();
5997                comp = intent.getComponent();
5998            }
5999        }
6000        if (comp != null) {
6001            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6002            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6003            if (si != null) {
6004                final ResolveInfo ri = new ResolveInfo();
6005                ri.serviceInfo = si;
6006                list.add(ri);
6007            }
6008            return list;
6009        }
6010
6011        // reader
6012        synchronized (mPackages) {
6013            String pkgName = intent.getPackage();
6014            if (pkgName == null) {
6015                return mServices.queryIntent(intent, resolvedType, flags, userId);
6016            }
6017            final PackageParser.Package pkg = mPackages.get(pkgName);
6018            if (pkg != null) {
6019                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6020                        userId);
6021            }
6022            return Collections.emptyList();
6023        }
6024    }
6025
6026    @Override
6027    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6028            String resolvedType, int flags, int userId) {
6029        return new ParceledListSlice<>(
6030                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6031    }
6032
6033    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6034            Intent intent, String resolvedType, int flags, int userId) {
6035        if (!sUserManager.exists(userId)) return Collections.emptyList();
6036        flags = updateFlagsForResolve(flags, userId, intent);
6037        ComponentName comp = intent.getComponent();
6038        if (comp == null) {
6039            if (intent.getSelector() != null) {
6040                intent = intent.getSelector();
6041                comp = intent.getComponent();
6042            }
6043        }
6044        if (comp != null) {
6045            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6046            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6047            if (pi != null) {
6048                final ResolveInfo ri = new ResolveInfo();
6049                ri.providerInfo = pi;
6050                list.add(ri);
6051            }
6052            return list;
6053        }
6054
6055        // reader
6056        synchronized (mPackages) {
6057            String pkgName = intent.getPackage();
6058            if (pkgName == null) {
6059                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6060            }
6061            final PackageParser.Package pkg = mPackages.get(pkgName);
6062            if (pkg != null) {
6063                return mProviders.queryIntentForPackage(
6064                        intent, resolvedType, flags, pkg.providers, userId);
6065            }
6066            return Collections.emptyList();
6067        }
6068    }
6069
6070    @Override
6071    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6072        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6073        flags = updateFlagsForPackage(flags, userId, null);
6074        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6075        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6076                true /* requireFullPermission */, false /* checkShell */,
6077                "get installed packages");
6078
6079        // writer
6080        synchronized (mPackages) {
6081            ArrayList<PackageInfo> list;
6082            if (listUninstalled) {
6083                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6084                for (PackageSetting ps : mSettings.mPackages.values()) {
6085                    final PackageInfo pi;
6086                    if (ps.pkg != null) {
6087                        pi = generatePackageInfo(ps, flags, userId);
6088                    } else {
6089                        pi = generatePackageInfo(ps, flags, userId);
6090                    }
6091                    if (pi != null) {
6092                        list.add(pi);
6093                    }
6094                }
6095            } else {
6096                list = new ArrayList<PackageInfo>(mPackages.size());
6097                for (PackageParser.Package p : mPackages.values()) {
6098                    final PackageInfo pi =
6099                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6100                    if (pi != null) {
6101                        list.add(pi);
6102                    }
6103                }
6104            }
6105
6106            return new ParceledListSlice<PackageInfo>(list);
6107        }
6108    }
6109
6110    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6111            String[] permissions, boolean[] tmp, int flags, int userId) {
6112        int numMatch = 0;
6113        final PermissionsState permissionsState = ps.getPermissionsState();
6114        for (int i=0; i<permissions.length; i++) {
6115            final String permission = permissions[i];
6116            if (permissionsState.hasPermission(permission, userId)) {
6117                tmp[i] = true;
6118                numMatch++;
6119            } else {
6120                tmp[i] = false;
6121            }
6122        }
6123        if (numMatch == 0) {
6124            return;
6125        }
6126        final PackageInfo pi;
6127        if (ps.pkg != null) {
6128            pi = generatePackageInfo(ps, flags, userId);
6129        } else {
6130            pi = generatePackageInfo(ps, flags, userId);
6131        }
6132        // The above might return null in cases of uninstalled apps or install-state
6133        // skew across users/profiles.
6134        if (pi != null) {
6135            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6136                if (numMatch == permissions.length) {
6137                    pi.requestedPermissions = permissions;
6138                } else {
6139                    pi.requestedPermissions = new String[numMatch];
6140                    numMatch = 0;
6141                    for (int i=0; i<permissions.length; i++) {
6142                        if (tmp[i]) {
6143                            pi.requestedPermissions[numMatch] = permissions[i];
6144                            numMatch++;
6145                        }
6146                    }
6147                }
6148            }
6149            list.add(pi);
6150        }
6151    }
6152
6153    @Override
6154    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6155            String[] permissions, int flags, int userId) {
6156        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6157        flags = updateFlagsForPackage(flags, userId, permissions);
6158        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6159
6160        // writer
6161        synchronized (mPackages) {
6162            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6163            boolean[] tmpBools = new boolean[permissions.length];
6164            if (listUninstalled) {
6165                for (PackageSetting ps : mSettings.mPackages.values()) {
6166                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6167                }
6168            } else {
6169                for (PackageParser.Package pkg : mPackages.values()) {
6170                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6171                    if (ps != null) {
6172                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6173                                userId);
6174                    }
6175                }
6176            }
6177
6178            return new ParceledListSlice<PackageInfo>(list);
6179        }
6180    }
6181
6182    @Override
6183    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6184        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6185        flags = updateFlagsForApplication(flags, userId, null);
6186        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6187
6188        // writer
6189        synchronized (mPackages) {
6190            ArrayList<ApplicationInfo> list;
6191            if (listUninstalled) {
6192                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6193                for (PackageSetting ps : mSettings.mPackages.values()) {
6194                    ApplicationInfo ai;
6195                    if (ps.pkg != null) {
6196                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6197                                ps.readUserState(userId), userId);
6198                    } else {
6199                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6200                    }
6201                    if (ai != null) {
6202                        list.add(ai);
6203                    }
6204                }
6205            } else {
6206                list = new ArrayList<ApplicationInfo>(mPackages.size());
6207                for (PackageParser.Package p : mPackages.values()) {
6208                    if (p.mExtras != null) {
6209                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6210                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6211                        if (ai != null) {
6212                            list.add(ai);
6213                        }
6214                    }
6215                }
6216            }
6217
6218            return new ParceledListSlice<ApplicationInfo>(list);
6219        }
6220    }
6221
6222    @Override
6223    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6224        if (DISABLE_EPHEMERAL_APPS) {
6225            return null;
6226        }
6227
6228        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6229                "getEphemeralApplications");
6230        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6231                true /* requireFullPermission */, false /* checkShell */,
6232                "getEphemeralApplications");
6233        synchronized (mPackages) {
6234            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6235                    .getEphemeralApplicationsLPw(userId);
6236            if (ephemeralApps != null) {
6237                return new ParceledListSlice<>(ephemeralApps);
6238            }
6239        }
6240        return null;
6241    }
6242
6243    @Override
6244    public boolean isEphemeralApplication(String packageName, int userId) {
6245        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6246                true /* requireFullPermission */, false /* checkShell */,
6247                "isEphemeral");
6248        if (DISABLE_EPHEMERAL_APPS) {
6249            return false;
6250        }
6251
6252        if (!isCallerSameApp(packageName)) {
6253            return false;
6254        }
6255        synchronized (mPackages) {
6256            PackageParser.Package pkg = mPackages.get(packageName);
6257            if (pkg != null) {
6258                return pkg.applicationInfo.isEphemeralApp();
6259            }
6260        }
6261        return false;
6262    }
6263
6264    @Override
6265    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6266        if (DISABLE_EPHEMERAL_APPS) {
6267            return null;
6268        }
6269
6270        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6271                true /* requireFullPermission */, false /* checkShell */,
6272                "getCookie");
6273        if (!isCallerSameApp(packageName)) {
6274            return null;
6275        }
6276        synchronized (mPackages) {
6277            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6278                    packageName, userId);
6279        }
6280    }
6281
6282    @Override
6283    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6284        if (DISABLE_EPHEMERAL_APPS) {
6285            return true;
6286        }
6287
6288        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6289                true /* requireFullPermission */, true /* checkShell */,
6290                "setCookie");
6291        if (!isCallerSameApp(packageName)) {
6292            return false;
6293        }
6294        synchronized (mPackages) {
6295            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6296                    packageName, cookie, userId);
6297        }
6298    }
6299
6300    @Override
6301    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6302        if (DISABLE_EPHEMERAL_APPS) {
6303            return null;
6304        }
6305
6306        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6307                "getEphemeralApplicationIcon");
6308        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6309                true /* requireFullPermission */, false /* checkShell */,
6310                "getEphemeralApplicationIcon");
6311        synchronized (mPackages) {
6312            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6313                    packageName, userId);
6314        }
6315    }
6316
6317    private boolean isCallerSameApp(String packageName) {
6318        PackageParser.Package pkg = mPackages.get(packageName);
6319        return pkg != null
6320                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6321    }
6322
6323    @Override
6324    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6325        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6326    }
6327
6328    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6329        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6330
6331        // reader
6332        synchronized (mPackages) {
6333            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6334            final int userId = UserHandle.getCallingUserId();
6335            while (i.hasNext()) {
6336                final PackageParser.Package p = i.next();
6337                if (p.applicationInfo == null) continue;
6338
6339                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6340                        && !p.applicationInfo.isDirectBootAware();
6341                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6342                        && p.applicationInfo.isDirectBootAware();
6343
6344                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6345                        && (!mSafeMode || isSystemApp(p))
6346                        && (matchesUnaware || matchesAware)) {
6347                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6348                    if (ps != null) {
6349                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6350                                ps.readUserState(userId), userId);
6351                        if (ai != null) {
6352                            finalList.add(ai);
6353                        }
6354                    }
6355                }
6356            }
6357        }
6358
6359        return finalList;
6360    }
6361
6362    @Override
6363    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6364        if (!sUserManager.exists(userId)) return null;
6365        flags = updateFlagsForComponent(flags, userId, name);
6366        // reader
6367        synchronized (mPackages) {
6368            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6369            PackageSetting ps = provider != null
6370                    ? mSettings.mPackages.get(provider.owner.packageName)
6371                    : null;
6372            return ps != null
6373                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6374                    ? PackageParser.generateProviderInfo(provider, flags,
6375                            ps.readUserState(userId), userId)
6376                    : null;
6377        }
6378    }
6379
6380    /**
6381     * @deprecated
6382     */
6383    @Deprecated
6384    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6385        // reader
6386        synchronized (mPackages) {
6387            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6388                    .entrySet().iterator();
6389            final int userId = UserHandle.getCallingUserId();
6390            while (i.hasNext()) {
6391                Map.Entry<String, PackageParser.Provider> entry = i.next();
6392                PackageParser.Provider p = entry.getValue();
6393                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6394
6395                if (ps != null && p.syncable
6396                        && (!mSafeMode || (p.info.applicationInfo.flags
6397                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6398                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6399                            ps.readUserState(userId), userId);
6400                    if (info != null) {
6401                        outNames.add(entry.getKey());
6402                        outInfo.add(info);
6403                    }
6404                }
6405            }
6406        }
6407    }
6408
6409    @Override
6410    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6411            int uid, int flags) {
6412        final int userId = processName != null ? UserHandle.getUserId(uid)
6413                : UserHandle.getCallingUserId();
6414        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6415        flags = updateFlagsForComponent(flags, userId, processName);
6416
6417        ArrayList<ProviderInfo> finalList = null;
6418        // reader
6419        synchronized (mPackages) {
6420            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6421            while (i.hasNext()) {
6422                final PackageParser.Provider p = i.next();
6423                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6424                if (ps != null && p.info.authority != null
6425                        && (processName == null
6426                                || (p.info.processName.equals(processName)
6427                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6428                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6429                    if (finalList == null) {
6430                        finalList = new ArrayList<ProviderInfo>(3);
6431                    }
6432                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6433                            ps.readUserState(userId), userId);
6434                    if (info != null) {
6435                        finalList.add(info);
6436                    }
6437                }
6438            }
6439        }
6440
6441        if (finalList != null) {
6442            Collections.sort(finalList, mProviderInitOrderSorter);
6443            return new ParceledListSlice<ProviderInfo>(finalList);
6444        }
6445
6446        return ParceledListSlice.emptyList();
6447    }
6448
6449    @Override
6450    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6451        // reader
6452        synchronized (mPackages) {
6453            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6454            return PackageParser.generateInstrumentationInfo(i, flags);
6455        }
6456    }
6457
6458    @Override
6459    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6460            String targetPackage, int flags) {
6461        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6462    }
6463
6464    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6465            int flags) {
6466        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6467
6468        // reader
6469        synchronized (mPackages) {
6470            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6471            while (i.hasNext()) {
6472                final PackageParser.Instrumentation p = i.next();
6473                if (targetPackage == null
6474                        || targetPackage.equals(p.info.targetPackage)) {
6475                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6476                            flags);
6477                    if (ii != null) {
6478                        finalList.add(ii);
6479                    }
6480                }
6481            }
6482        }
6483
6484        return finalList;
6485    }
6486
6487    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6488        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6489        if (overlays == null) {
6490            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6491            return;
6492        }
6493        for (PackageParser.Package opkg : overlays.values()) {
6494            // Not much to do if idmap fails: we already logged the error
6495            // and we certainly don't want to abort installation of pkg simply
6496            // because an overlay didn't fit properly. For these reasons,
6497            // ignore the return value of createIdmapForPackagePairLI.
6498            createIdmapForPackagePairLI(pkg, opkg);
6499        }
6500    }
6501
6502    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6503            PackageParser.Package opkg) {
6504        if (!opkg.mTrustedOverlay) {
6505            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6506                    opkg.baseCodePath + ": overlay not trusted");
6507            return false;
6508        }
6509        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6510        if (overlaySet == null) {
6511            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6512                    opkg.baseCodePath + " but target package has no known overlays");
6513            return false;
6514        }
6515        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6516        // TODO: generate idmap for split APKs
6517        try {
6518            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6519        } catch (InstallerException e) {
6520            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6521                    + opkg.baseCodePath);
6522            return false;
6523        }
6524        PackageParser.Package[] overlayArray =
6525            overlaySet.values().toArray(new PackageParser.Package[0]);
6526        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6527            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6528                return p1.mOverlayPriority - p2.mOverlayPriority;
6529            }
6530        };
6531        Arrays.sort(overlayArray, cmp);
6532
6533        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6534        int i = 0;
6535        for (PackageParser.Package p : overlayArray) {
6536            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6537        }
6538        return true;
6539    }
6540
6541    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6542        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
6543        try {
6544            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6545        } finally {
6546            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6547        }
6548    }
6549
6550    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6551        final File[] files = dir.listFiles();
6552        if (ArrayUtils.isEmpty(files)) {
6553            Log.d(TAG, "No files in app dir " + dir);
6554            return;
6555        }
6556
6557        if (DEBUG_PACKAGE_SCANNING) {
6558            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6559                    + " flags=0x" + Integer.toHexString(parseFlags));
6560        }
6561
6562        for (File file : files) {
6563            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6564                    && !PackageInstallerService.isStageName(file.getName());
6565            if (!isPackage) {
6566                // Ignore entries which are not packages
6567                continue;
6568            }
6569            try {
6570                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6571                        scanFlags, currentTime, null);
6572            } catch (PackageManagerException e) {
6573                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6574
6575                // Delete invalid userdata apps
6576                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6577                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6578                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6579                    removeCodePathLI(file);
6580                }
6581            }
6582        }
6583    }
6584
6585    private static File getSettingsProblemFile() {
6586        File dataDir = Environment.getDataDirectory();
6587        File systemDir = new File(dataDir, "system");
6588        File fname = new File(systemDir, "uiderrors.txt");
6589        return fname;
6590    }
6591
6592    static void reportSettingsProblem(int priority, String msg) {
6593        logCriticalInfo(priority, msg);
6594    }
6595
6596    static void logCriticalInfo(int priority, String msg) {
6597        Slog.println(priority, TAG, msg);
6598        EventLogTags.writePmCriticalInfo(msg);
6599        try {
6600            File fname = getSettingsProblemFile();
6601            FileOutputStream out = new FileOutputStream(fname, true);
6602            PrintWriter pw = new FastPrintWriter(out);
6603            SimpleDateFormat formatter = new SimpleDateFormat();
6604            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6605            pw.println(dateString + ": " + msg);
6606            pw.close();
6607            FileUtils.setPermissions(
6608                    fname.toString(),
6609                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6610                    -1, -1);
6611        } catch (java.io.IOException e) {
6612        }
6613    }
6614
6615    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
6616        if (srcFile.isDirectory()) {
6617            final File baseFile = new File(pkg.baseCodePath);
6618            long maxModifiedTime = baseFile.lastModified();
6619            if (pkg.splitCodePaths != null) {
6620                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
6621                    final File splitFile = new File(pkg.splitCodePaths[i]);
6622                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
6623                }
6624            }
6625            return maxModifiedTime;
6626        }
6627        return srcFile.lastModified();
6628    }
6629
6630    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6631            final int policyFlags) throws PackageManagerException {
6632        if (ps != null
6633                && ps.codePath.equals(srcFile)
6634                && ps.timeStamp == getLastModifiedTime(pkg, srcFile)
6635                && !isCompatSignatureUpdateNeeded(pkg)
6636                && !isRecoverSignatureUpdateNeeded(pkg)) {
6637            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6638            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6639            ArraySet<PublicKey> signingKs;
6640            synchronized (mPackages) {
6641                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6642            }
6643            if (ps.signatures.mSignatures != null
6644                    && ps.signatures.mSignatures.length != 0
6645                    && signingKs != null) {
6646                // Optimization: reuse the existing cached certificates
6647                // if the package appears to be unchanged.
6648                pkg.mSignatures = ps.signatures.mSignatures;
6649                pkg.mSigningKeys = signingKs;
6650                return;
6651            }
6652
6653            Slog.w(TAG, "PackageSetting for " + ps.name
6654                    + " is missing signatures.  Collecting certs again to recover them.");
6655        } else {
6656            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6657        }
6658
6659        try {
6660            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
6661            PackageParser.collectCertificates(pkg, policyFlags);
6662        } catch (PackageParserException e) {
6663            throw PackageManagerException.from(e);
6664        } finally {
6665            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6666        }
6667    }
6668
6669    /**
6670     *  Traces a package scan.
6671     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6672     */
6673    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6674            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6675        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
6676        try {
6677            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6678        } finally {
6679            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6680        }
6681    }
6682
6683    /**
6684     *  Scans a package and returns the newly parsed package.
6685     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6686     */
6687    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6688            long currentTime, UserHandle user) throws PackageManagerException {
6689        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6690        PackageParser pp = new PackageParser();
6691        pp.setSeparateProcesses(mSeparateProcesses);
6692        pp.setOnlyCoreApps(mOnlyCore);
6693        pp.setDisplayMetrics(mMetrics);
6694
6695        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6696            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6697        }
6698
6699        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6700        final PackageParser.Package pkg;
6701        try {
6702            pkg = pp.parsePackage(scanFile, parseFlags);
6703        } catch (PackageParserException e) {
6704            throw PackageManagerException.from(e);
6705        } finally {
6706            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6707        }
6708
6709        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6710    }
6711
6712    /**
6713     *  Scans a package and returns the newly parsed package.
6714     *  @throws PackageManagerException on a parse error.
6715     */
6716    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6717            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6718            throws PackageManagerException {
6719        // If the package has children and this is the first dive in the function
6720        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6721        // packages (parent and children) would be successfully scanned before the
6722        // actual scan since scanning mutates internal state and we want to atomically
6723        // install the package and its children.
6724        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6725            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6726                scanFlags |= SCAN_CHECK_ONLY;
6727            }
6728        } else {
6729            scanFlags &= ~SCAN_CHECK_ONLY;
6730        }
6731
6732        // Scan the parent
6733        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6734                scanFlags, currentTime, user);
6735
6736        // Scan the children
6737        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6738        for (int i = 0; i < childCount; i++) {
6739            PackageParser.Package childPackage = pkg.childPackages.get(i);
6740            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6741                    currentTime, user);
6742        }
6743
6744
6745        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6746            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6747        }
6748
6749        return scannedPkg;
6750    }
6751
6752    /**
6753     *  Scans a package and returns the newly parsed package.
6754     *  @throws PackageManagerException on a parse error.
6755     */
6756    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6757            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6758            throws PackageManagerException {
6759        PackageSetting ps = null;
6760        PackageSetting updatedPkg;
6761        // reader
6762        synchronized (mPackages) {
6763            // Look to see if we already know about this package.
6764            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6765            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6766                // This package has been renamed to its original name.  Let's
6767                // use that.
6768                ps = mSettings.peekPackageLPr(oldName);
6769            }
6770            // If there was no original package, see one for the real package name.
6771            if (ps == null) {
6772                ps = mSettings.peekPackageLPr(pkg.packageName);
6773            }
6774            // Check to see if this package could be hiding/updating a system
6775            // package.  Must look for it either under the original or real
6776            // package name depending on our state.
6777            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6778            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6779
6780            // If this is a package we don't know about on the system partition, we
6781            // may need to remove disabled child packages on the system partition
6782            // or may need to not add child packages if the parent apk is updated
6783            // on the data partition and no longer defines this child package.
6784            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6785                // If this is a parent package for an updated system app and this system
6786                // app got an OTA update which no longer defines some of the child packages
6787                // we have to prune them from the disabled system packages.
6788                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6789                if (disabledPs != null) {
6790                    final int scannedChildCount = (pkg.childPackages != null)
6791                            ? pkg.childPackages.size() : 0;
6792                    final int disabledChildCount = disabledPs.childPackageNames != null
6793                            ? disabledPs.childPackageNames.size() : 0;
6794                    for (int i = 0; i < disabledChildCount; i++) {
6795                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6796                        boolean disabledPackageAvailable = false;
6797                        for (int j = 0; j < scannedChildCount; j++) {
6798                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6799                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6800                                disabledPackageAvailable = true;
6801                                break;
6802                            }
6803                         }
6804                         if (!disabledPackageAvailable) {
6805                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6806                         }
6807                    }
6808                }
6809            }
6810        }
6811
6812        boolean updatedPkgBetter = false;
6813        // First check if this is a system package that may involve an update
6814        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6815            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6816            // it needs to drop FLAG_PRIVILEGED.
6817            if (locationIsPrivileged(scanFile)) {
6818                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6819            } else {
6820                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6821            }
6822
6823            if (ps != null && !ps.codePath.equals(scanFile)) {
6824                // The path has changed from what was last scanned...  check the
6825                // version of the new path against what we have stored to determine
6826                // what to do.
6827                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6828                if (pkg.mVersionCode <= ps.versionCode) {
6829                    // The system package has been updated and the code path does not match
6830                    // Ignore entry. Skip it.
6831                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6832                            + " ignored: updated version " + ps.versionCode
6833                            + " better than this " + pkg.mVersionCode);
6834                    if (!updatedPkg.codePath.equals(scanFile)) {
6835                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6836                                + ps.name + " changing from " + updatedPkg.codePathString
6837                                + " to " + scanFile);
6838                        updatedPkg.codePath = scanFile;
6839                        updatedPkg.codePathString = scanFile.toString();
6840                        updatedPkg.resourcePath = scanFile;
6841                        updatedPkg.resourcePathString = scanFile.toString();
6842                    }
6843                    updatedPkg.pkg = pkg;
6844                    updatedPkg.versionCode = pkg.mVersionCode;
6845
6846                    // Update the disabled system child packages to point to the package too.
6847                    final int childCount = updatedPkg.childPackageNames != null
6848                            ? updatedPkg.childPackageNames.size() : 0;
6849                    for (int i = 0; i < childCount; i++) {
6850                        String childPackageName = updatedPkg.childPackageNames.get(i);
6851                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6852                                childPackageName);
6853                        if (updatedChildPkg != null) {
6854                            updatedChildPkg.pkg = pkg;
6855                            updatedChildPkg.versionCode = pkg.mVersionCode;
6856                        }
6857                    }
6858
6859                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6860                            + scanFile + " ignored: updated version " + ps.versionCode
6861                            + " better than this " + pkg.mVersionCode);
6862                } else {
6863                    // The current app on the system partition is better than
6864                    // what we have updated to on the data partition; switch
6865                    // back to the system partition version.
6866                    // At this point, its safely assumed that package installation for
6867                    // apps in system partition will go through. If not there won't be a working
6868                    // version of the app
6869                    // writer
6870                    synchronized (mPackages) {
6871                        // Just remove the loaded entries from package lists.
6872                        mPackages.remove(ps.name);
6873                    }
6874
6875                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6876                            + " reverting from " + ps.codePathString
6877                            + ": new version " + pkg.mVersionCode
6878                            + " better than installed " + ps.versionCode);
6879
6880                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6881                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6882                    synchronized (mInstallLock) {
6883                        args.cleanUpResourcesLI();
6884                    }
6885                    synchronized (mPackages) {
6886                        mSettings.enableSystemPackageLPw(ps.name);
6887                    }
6888                    updatedPkgBetter = true;
6889                }
6890            }
6891        }
6892
6893        if (updatedPkg != null) {
6894            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6895            // initially
6896            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
6897
6898            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6899            // flag set initially
6900            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6901                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6902            }
6903        }
6904
6905        // Verify certificates against what was last scanned
6906        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
6907
6908        /*
6909         * A new system app appeared, but we already had a non-system one of the
6910         * same name installed earlier.
6911         */
6912        boolean shouldHideSystemApp = false;
6913        if (updatedPkg == null && ps != null
6914                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6915            /*
6916             * Check to make sure the signatures match first. If they don't,
6917             * wipe the installed application and its data.
6918             */
6919            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6920                    != PackageManager.SIGNATURE_MATCH) {
6921                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6922                        + " signatures don't match existing userdata copy; removing");
6923                try (PackageFreezer freezer = freezePackage(pkg.packageName,
6924                        "scanPackageInternalLI")) {
6925                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
6926                }
6927                ps = null;
6928            } else {
6929                /*
6930                 * If the newly-added system app is an older version than the
6931                 * already installed version, hide it. It will be scanned later
6932                 * and re-added like an update.
6933                 */
6934                if (pkg.mVersionCode <= ps.versionCode) {
6935                    shouldHideSystemApp = true;
6936                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6937                            + " but new version " + pkg.mVersionCode + " better than installed "
6938                            + ps.versionCode + "; hiding system");
6939                } else {
6940                    /*
6941                     * The newly found system app is a newer version that the
6942                     * one previously installed. Simply remove the
6943                     * already-installed application and replace it with our own
6944                     * while keeping the application data.
6945                     */
6946                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6947                            + " reverting from " + ps.codePathString + ": new version "
6948                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6949                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6950                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6951                    synchronized (mInstallLock) {
6952                        args.cleanUpResourcesLI();
6953                    }
6954                }
6955            }
6956        }
6957
6958        // The apk is forward locked (not public) if its code and resources
6959        // are kept in different files. (except for app in either system or
6960        // vendor path).
6961        // TODO grab this value from PackageSettings
6962        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6963            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6964                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
6965            }
6966        }
6967
6968        // TODO: extend to support forward-locked splits
6969        String resourcePath = null;
6970        String baseResourcePath = null;
6971        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6972            if (ps != null && ps.resourcePathString != null) {
6973                resourcePath = ps.resourcePathString;
6974                baseResourcePath = ps.resourcePathString;
6975            } else {
6976                // Should not happen at all. Just log an error.
6977                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6978            }
6979        } else {
6980            resourcePath = pkg.codePath;
6981            baseResourcePath = pkg.baseCodePath;
6982        }
6983
6984        // Set application objects path explicitly.
6985        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6986        pkg.setApplicationInfoCodePath(pkg.codePath);
6987        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6988        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6989        pkg.setApplicationInfoResourcePath(resourcePath);
6990        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6991        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6992
6993        // Note that we invoke the following method only if we are about to unpack an application
6994        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
6995                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6996
6997        /*
6998         * If the system app should be overridden by a previously installed
6999         * data, hide the system app now and let the /data/app scan pick it up
7000         * again.
7001         */
7002        if (shouldHideSystemApp) {
7003            synchronized (mPackages) {
7004                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7005            }
7006        }
7007
7008        return scannedPkg;
7009    }
7010
7011    private static String fixProcessName(String defProcessName,
7012            String processName, int uid) {
7013        if (processName == null) {
7014            return defProcessName;
7015        }
7016        return processName;
7017    }
7018
7019    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7020            throws PackageManagerException {
7021        if (pkgSetting.signatures.mSignatures != null) {
7022            // Already existing package. Make sure signatures match
7023            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7024                    == PackageManager.SIGNATURE_MATCH;
7025            if (!match) {
7026                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7027                        == PackageManager.SIGNATURE_MATCH;
7028            }
7029            if (!match) {
7030                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7031                        == PackageManager.SIGNATURE_MATCH;
7032            }
7033            if (!match) {
7034                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7035                        + pkg.packageName + " signatures do not match the "
7036                        + "previously installed version; ignoring!");
7037            }
7038        }
7039
7040        // Check for shared user signatures
7041        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7042            // Already existing package. Make sure signatures match
7043            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7044                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7045            if (!match) {
7046                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7047                        == PackageManager.SIGNATURE_MATCH;
7048            }
7049            if (!match) {
7050                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7051                        == PackageManager.SIGNATURE_MATCH;
7052            }
7053            if (!match) {
7054                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7055                        "Package " + pkg.packageName
7056                        + " has no signatures that match those in shared user "
7057                        + pkgSetting.sharedUser.name + "; ignoring!");
7058            }
7059        }
7060    }
7061
7062    /**
7063     * Enforces that only the system UID or root's UID can call a method exposed
7064     * via Binder.
7065     *
7066     * @param message used as message if SecurityException is thrown
7067     * @throws SecurityException if the caller is not system or root
7068     */
7069    private static final void enforceSystemOrRoot(String message) {
7070        final int uid = Binder.getCallingUid();
7071        if (uid != Process.SYSTEM_UID && uid != 0) {
7072            throw new SecurityException(message);
7073        }
7074    }
7075
7076    @Override
7077    public void performFstrimIfNeeded() {
7078        enforceSystemOrRoot("Only the system can request fstrim");
7079
7080        // Before everything else, see whether we need to fstrim.
7081        try {
7082            IMountService ms = PackageHelper.getMountService();
7083            if (ms != null) {
7084                boolean doTrim = false;
7085                final long interval = android.provider.Settings.Global.getLong(
7086                        mContext.getContentResolver(),
7087                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7088                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7089                if (interval > 0) {
7090                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7091                    if (timeSinceLast > interval) {
7092                        doTrim = true;
7093                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7094                                + "; running immediately");
7095                    }
7096                }
7097                if (doTrim) {
7098                    if (!isFirstBoot()) {
7099                        try {
7100                            ActivityManagerNative.getDefault().showBootMessage(
7101                                    mContext.getResources().getString(
7102                                            R.string.android_upgrading_fstrim), true);
7103                        } catch (RemoteException e) {
7104                        }
7105                    }
7106                    ms.runMaintenance();
7107                }
7108            } else {
7109                Slog.e(TAG, "Mount service unavailable!");
7110            }
7111        } catch (RemoteException e) {
7112            // Can't happen; MountService is local
7113        }
7114    }
7115
7116    @Override
7117    public void updatePackagesIfNeeded() {
7118        enforceSystemOrRoot("Only the system can request package update");
7119
7120        // We need to re-extract after an OTA.
7121        boolean causeUpgrade = isUpgrade();
7122
7123        // First boot or factory reset.
7124        // Note: we also handle devices that are upgrading to N right now as if it is their
7125        //       first boot, as they do not have profile data.
7126        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7127
7128        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7129        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7130
7131        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7132            return;
7133        }
7134
7135        List<PackageParser.Package> pkgs;
7136        synchronized (mPackages) {
7137            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7138        }
7139
7140        final long startTime = System.nanoTime();
7141        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
7142                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7143
7144        final int elapsedTimeSeconds =
7145                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7146
7147        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7148        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7149        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7150        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7151        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7152    }
7153
7154    /**
7155     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7156     * containing statistics about the invocation. The array consists of three elements,
7157     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7158     * and {@code numberOfPackagesFailed}.
7159     */
7160    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
7161            String compilerFilter) {
7162
7163        int numberOfPackagesVisited = 0;
7164        int numberOfPackagesOptimized = 0;
7165        int numberOfPackagesSkipped = 0;
7166        int numberOfPackagesFailed = 0;
7167        final int numberOfPackagesToDexopt = pkgs.size();
7168
7169        for (PackageParser.Package pkg : pkgs) {
7170            numberOfPackagesVisited++;
7171
7172            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7173                if (DEBUG_DEXOPT) {
7174                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7175                }
7176                numberOfPackagesSkipped++;
7177                continue;
7178            }
7179
7180            if (DEBUG_DEXOPT) {
7181                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7182                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7183            }
7184
7185            if (showDialog) {
7186                try {
7187                    ActivityManagerNative.getDefault().showBootMessage(
7188                            mContext.getResources().getString(R.string.android_upgrading_apk,
7189                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7190                } catch (RemoteException e) {
7191                }
7192            }
7193
7194            // If the OTA updates a system app which was previously preopted to a non-preopted state
7195            // the app might end up being verified at runtime. That's because by default the apps
7196            // are verify-profile but for preopted apps there's no profile.
7197            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
7198            // that before the OTA the app was preopted) the app gets compiled with a non-profile
7199            // filter (by default interpret-only).
7200            // Note that at this stage unused apps are already filtered.
7201            if (isSystemApp(pkg) &&
7202                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
7203                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
7204                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
7205            }
7206
7207            // checkProfiles is false to avoid merging profiles during boot which
7208            // might interfere with background compilation (b/28612421).
7209            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7210            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7211            // trade-off worth doing to save boot time work.
7212            int dexOptStatus = performDexOptTraced(pkg.packageName,
7213                    false /* checkProfiles */,
7214                    compilerFilter,
7215                    false /* force */);
7216            switch (dexOptStatus) {
7217                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7218                    numberOfPackagesOptimized++;
7219                    break;
7220                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7221                    numberOfPackagesSkipped++;
7222                    break;
7223                case PackageDexOptimizer.DEX_OPT_FAILED:
7224                    numberOfPackagesFailed++;
7225                    break;
7226                default:
7227                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7228                    break;
7229            }
7230        }
7231
7232        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7233                numberOfPackagesFailed };
7234    }
7235
7236    @Override
7237    public void notifyPackageUse(String packageName, int reason) {
7238        synchronized (mPackages) {
7239            PackageParser.Package p = mPackages.get(packageName);
7240            if (p == null) {
7241                return;
7242            }
7243            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7244        }
7245    }
7246
7247    // TODO: this is not used nor needed. Delete it.
7248    @Override
7249    public boolean performDexOptIfNeeded(String packageName) {
7250        int dexOptStatus = performDexOptTraced(packageName,
7251                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7252        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7253    }
7254
7255    @Override
7256    public boolean performDexOpt(String packageName,
7257            boolean checkProfiles, int compileReason, boolean force) {
7258        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7259                getCompilerFilterForReason(compileReason), force);
7260        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7261    }
7262
7263    @Override
7264    public boolean performDexOptMode(String packageName,
7265            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7266        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7267                targetCompilerFilter, force);
7268        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7269    }
7270
7271    private int performDexOptTraced(String packageName,
7272                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7273        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7274        try {
7275            return performDexOptInternal(packageName, checkProfiles,
7276                    targetCompilerFilter, force);
7277        } finally {
7278            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7279        }
7280    }
7281
7282    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7283    // if the package can now be considered up to date for the given filter.
7284    private int performDexOptInternal(String packageName,
7285                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7286        PackageParser.Package p;
7287        synchronized (mPackages) {
7288            p = mPackages.get(packageName);
7289            if (p == null) {
7290                // Package could not be found. Report failure.
7291                return PackageDexOptimizer.DEX_OPT_FAILED;
7292            }
7293            mPackageUsage.maybeWriteAsync(mPackages);
7294            mCompilerStats.maybeWriteAsync();
7295        }
7296        long callingId = Binder.clearCallingIdentity();
7297        try {
7298            synchronized (mInstallLock) {
7299                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7300                        targetCompilerFilter, force);
7301            }
7302        } finally {
7303            Binder.restoreCallingIdentity(callingId);
7304        }
7305    }
7306
7307    public ArraySet<String> getOptimizablePackages() {
7308        ArraySet<String> pkgs = new ArraySet<String>();
7309        synchronized (mPackages) {
7310            for (PackageParser.Package p : mPackages.values()) {
7311                if (PackageDexOptimizer.canOptimizePackage(p)) {
7312                    pkgs.add(p.packageName);
7313                }
7314            }
7315        }
7316        return pkgs;
7317    }
7318
7319    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7320            boolean checkProfiles, String targetCompilerFilter,
7321            boolean force) {
7322        // Select the dex optimizer based on the force parameter.
7323        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7324        //       allocate an object here.
7325        PackageDexOptimizer pdo = force
7326                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7327                : mPackageDexOptimizer;
7328
7329        // Optimize all dependencies first. Note: we ignore the return value and march on
7330        // on errors.
7331        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7332        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7333        if (!deps.isEmpty()) {
7334            for (PackageParser.Package depPackage : deps) {
7335                // TODO: Analyze and investigate if we (should) profile libraries.
7336                // Currently this will do a full compilation of the library by default.
7337                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7338                        false /* checkProfiles */,
7339                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY),
7340                        getOrCreateCompilerPackageStats(depPackage));
7341            }
7342        }
7343        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7344                targetCompilerFilter, getOrCreateCompilerPackageStats(p));
7345    }
7346
7347    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7348        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7349            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7350            Set<String> collectedNames = new HashSet<>();
7351            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7352
7353            retValue.remove(p);
7354
7355            return retValue;
7356        } else {
7357            return Collections.emptyList();
7358        }
7359    }
7360
7361    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7362            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7363        if (!collectedNames.contains(p.packageName)) {
7364            collectedNames.add(p.packageName);
7365            collected.add(p);
7366
7367            if (p.usesLibraries != null) {
7368                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7369            }
7370            if (p.usesOptionalLibraries != null) {
7371                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7372                        collectedNames);
7373            }
7374        }
7375    }
7376
7377    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7378            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7379        for (String libName : libs) {
7380            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7381            if (libPkg != null) {
7382                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7383            }
7384        }
7385    }
7386
7387    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7388        synchronized (mPackages) {
7389            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7390            if (lib != null && lib.apk != null) {
7391                return mPackages.get(lib.apk);
7392            }
7393        }
7394        return null;
7395    }
7396
7397    public void shutdown() {
7398        mPackageUsage.writeNow(mPackages);
7399        mCompilerStats.writeNow();
7400    }
7401
7402    @Override
7403    public void dumpProfiles(String packageName) {
7404        PackageParser.Package pkg;
7405        synchronized (mPackages) {
7406            pkg = mPackages.get(packageName);
7407            if (pkg == null) {
7408                throw new IllegalArgumentException("Unknown package: " + packageName);
7409            }
7410        }
7411        /* Only the shell, root, or the app user should be able to dump profiles. */
7412        int callingUid = Binder.getCallingUid();
7413        if (callingUid != Process.SHELL_UID &&
7414            callingUid != Process.ROOT_UID &&
7415            callingUid != pkg.applicationInfo.uid) {
7416            throw new SecurityException("dumpProfiles");
7417        }
7418
7419        synchronized (mInstallLock) {
7420            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7421            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7422            try {
7423                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7424                String gid = Integer.toString(sharedGid);
7425                String codePaths = TextUtils.join(";", allCodePaths);
7426                mInstaller.dumpProfiles(gid, packageName, codePaths);
7427            } catch (InstallerException e) {
7428                Slog.w(TAG, "Failed to dump profiles", e);
7429            }
7430            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7431        }
7432    }
7433
7434    @Override
7435    public void forceDexOpt(String packageName) {
7436        enforceSystemOrRoot("forceDexOpt");
7437
7438        PackageParser.Package pkg;
7439        synchronized (mPackages) {
7440            pkg = mPackages.get(packageName);
7441            if (pkg == null) {
7442                throw new IllegalArgumentException("Unknown package: " + packageName);
7443            }
7444        }
7445
7446        synchronized (mInstallLock) {
7447            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7448
7449            // Whoever is calling forceDexOpt wants a fully compiled package.
7450            // Don't use profiles since that may cause compilation to be skipped.
7451            final int res = performDexOptInternalWithDependenciesLI(pkg,
7452                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7453                    true /* force */);
7454
7455            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7456            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7457                throw new IllegalStateException("Failed to dexopt: " + res);
7458            }
7459        }
7460    }
7461
7462    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7463        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7464            Slog.w(TAG, "Unable to update from " + oldPkg.name
7465                    + " to " + newPkg.packageName
7466                    + ": old package not in system partition");
7467            return false;
7468        } else if (mPackages.get(oldPkg.name) != null) {
7469            Slog.w(TAG, "Unable to update from " + oldPkg.name
7470                    + " to " + newPkg.packageName
7471                    + ": old package still exists");
7472            return false;
7473        }
7474        return true;
7475    }
7476
7477    void removeCodePathLI(File codePath) {
7478        if (codePath.isDirectory()) {
7479            try {
7480                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7481            } catch (InstallerException e) {
7482                Slog.w(TAG, "Failed to remove code path", e);
7483            }
7484        } else {
7485            codePath.delete();
7486        }
7487    }
7488
7489    private int[] resolveUserIds(int userId) {
7490        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7491    }
7492
7493    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7494        if (pkg == null) {
7495            Slog.wtf(TAG, "Package was null!", new Throwable());
7496            return;
7497        }
7498        clearAppDataLeafLIF(pkg, userId, flags);
7499        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7500        for (int i = 0; i < childCount; i++) {
7501            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7502        }
7503    }
7504
7505    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7506        final PackageSetting ps;
7507        synchronized (mPackages) {
7508            ps = mSettings.mPackages.get(pkg.packageName);
7509        }
7510        for (int realUserId : resolveUserIds(userId)) {
7511            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7512            try {
7513                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7514                        ceDataInode);
7515            } catch (InstallerException e) {
7516                Slog.w(TAG, String.valueOf(e));
7517            }
7518        }
7519    }
7520
7521    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7522        if (pkg == null) {
7523            Slog.wtf(TAG, "Package was null!", new Throwable());
7524            return;
7525        }
7526        destroyAppDataLeafLIF(pkg, userId, flags);
7527        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7528        for (int i = 0; i < childCount; i++) {
7529            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7530        }
7531    }
7532
7533    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7534        final PackageSetting ps;
7535        synchronized (mPackages) {
7536            ps = mSettings.mPackages.get(pkg.packageName);
7537        }
7538        for (int realUserId : resolveUserIds(userId)) {
7539            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7540            try {
7541                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7542                        ceDataInode);
7543            } catch (InstallerException e) {
7544                Slog.w(TAG, String.valueOf(e));
7545            }
7546        }
7547    }
7548
7549    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7550        if (pkg == null) {
7551            Slog.wtf(TAG, "Package was null!", new Throwable());
7552            return;
7553        }
7554        destroyAppProfilesLeafLIF(pkg);
7555        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7556        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7557        for (int i = 0; i < childCount; i++) {
7558            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7559            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7560                    true /* removeBaseMarker */);
7561        }
7562    }
7563
7564    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7565            boolean removeBaseMarker) {
7566        if (pkg.isForwardLocked()) {
7567            return;
7568        }
7569
7570        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7571            try {
7572                path = PackageManagerServiceUtils.realpath(new File(path));
7573            } catch (IOException e) {
7574                // TODO: Should we return early here ?
7575                Slog.w(TAG, "Failed to get canonical path", e);
7576                continue;
7577            }
7578
7579            final String useMarker = path.replace('/', '@');
7580            for (int realUserId : resolveUserIds(userId)) {
7581                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7582                if (removeBaseMarker) {
7583                    File foreignUseMark = new File(profileDir, useMarker);
7584                    if (foreignUseMark.exists()) {
7585                        if (!foreignUseMark.delete()) {
7586                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7587                                    + pkg.packageName);
7588                        }
7589                    }
7590                }
7591
7592                File[] markers = profileDir.listFiles();
7593                if (markers != null) {
7594                    final String searchString = "@" + pkg.packageName + "@";
7595                    // We also delete all markers that contain the package name we're
7596                    // uninstalling. These are associated with secondary dex-files belonging
7597                    // to the package. Reconstructing the path of these dex files is messy
7598                    // in general.
7599                    for (File marker : markers) {
7600                        if (marker.getName().indexOf(searchString) > 0) {
7601                            if (!marker.delete()) {
7602                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7603                                    + pkg.packageName);
7604                            }
7605                        }
7606                    }
7607                }
7608            }
7609        }
7610    }
7611
7612    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7613        try {
7614            mInstaller.destroyAppProfiles(pkg.packageName);
7615        } catch (InstallerException e) {
7616            Slog.w(TAG, String.valueOf(e));
7617        }
7618    }
7619
7620    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7621        if (pkg == null) {
7622            Slog.wtf(TAG, "Package was null!", new Throwable());
7623            return;
7624        }
7625        clearAppProfilesLeafLIF(pkg);
7626        // We don't remove the base foreign use marker when clearing profiles because
7627        // we will rename it when the app is updated. Unlike the actual profile contents,
7628        // the foreign use marker is good across installs.
7629        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7630        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7631        for (int i = 0; i < childCount; i++) {
7632            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7633        }
7634    }
7635
7636    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7637        try {
7638            mInstaller.clearAppProfiles(pkg.packageName);
7639        } catch (InstallerException e) {
7640            Slog.w(TAG, String.valueOf(e));
7641        }
7642    }
7643
7644    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7645            long lastUpdateTime) {
7646        // Set parent install/update time
7647        PackageSetting ps = (PackageSetting) pkg.mExtras;
7648        if (ps != null) {
7649            ps.firstInstallTime = firstInstallTime;
7650            ps.lastUpdateTime = lastUpdateTime;
7651        }
7652        // Set children install/update time
7653        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7654        for (int i = 0; i < childCount; i++) {
7655            PackageParser.Package childPkg = pkg.childPackages.get(i);
7656            ps = (PackageSetting) childPkg.mExtras;
7657            if (ps != null) {
7658                ps.firstInstallTime = firstInstallTime;
7659                ps.lastUpdateTime = lastUpdateTime;
7660            }
7661        }
7662    }
7663
7664    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7665            PackageParser.Package changingLib) {
7666        if (file.path != null) {
7667            usesLibraryFiles.add(file.path);
7668            return;
7669        }
7670        PackageParser.Package p = mPackages.get(file.apk);
7671        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7672            // If we are doing this while in the middle of updating a library apk,
7673            // then we need to make sure to use that new apk for determining the
7674            // dependencies here.  (We haven't yet finished committing the new apk
7675            // to the package manager state.)
7676            if (p == null || p.packageName.equals(changingLib.packageName)) {
7677                p = changingLib;
7678            }
7679        }
7680        if (p != null) {
7681            usesLibraryFiles.addAll(p.getAllCodePaths());
7682        }
7683    }
7684
7685    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7686            PackageParser.Package changingLib) throws PackageManagerException {
7687        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7688            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7689            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7690            for (int i=0; i<N; i++) {
7691                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7692                if (file == null) {
7693                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7694                            "Package " + pkg.packageName + " requires unavailable shared library "
7695                            + pkg.usesLibraries.get(i) + "; failing!");
7696                }
7697                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7698            }
7699            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7700            for (int i=0; i<N; i++) {
7701                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7702                if (file == null) {
7703                    Slog.w(TAG, "Package " + pkg.packageName
7704                            + " desires unavailable shared library "
7705                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7706                } else {
7707                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7708                }
7709            }
7710            N = usesLibraryFiles.size();
7711            if (N > 0) {
7712                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7713            } else {
7714                pkg.usesLibraryFiles = null;
7715            }
7716        }
7717    }
7718
7719    private static boolean hasString(List<String> list, List<String> which) {
7720        if (list == null) {
7721            return false;
7722        }
7723        for (int i=list.size()-1; i>=0; i--) {
7724            for (int j=which.size()-1; j>=0; j--) {
7725                if (which.get(j).equals(list.get(i))) {
7726                    return true;
7727                }
7728            }
7729        }
7730        return false;
7731    }
7732
7733    private void updateAllSharedLibrariesLPw() {
7734        for (PackageParser.Package pkg : mPackages.values()) {
7735            try {
7736                updateSharedLibrariesLPw(pkg, null);
7737            } catch (PackageManagerException e) {
7738                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7739            }
7740        }
7741    }
7742
7743    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7744            PackageParser.Package changingPkg) {
7745        ArrayList<PackageParser.Package> res = null;
7746        for (PackageParser.Package pkg : mPackages.values()) {
7747            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7748                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7749                if (res == null) {
7750                    res = new ArrayList<PackageParser.Package>();
7751                }
7752                res.add(pkg);
7753                try {
7754                    updateSharedLibrariesLPw(pkg, changingPkg);
7755                } catch (PackageManagerException e) {
7756                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7757                }
7758            }
7759        }
7760        return res;
7761    }
7762
7763    /**
7764     * Derive the value of the {@code cpuAbiOverride} based on the provided
7765     * value and an optional stored value from the package settings.
7766     */
7767    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7768        String cpuAbiOverride = null;
7769
7770        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7771            cpuAbiOverride = null;
7772        } else if (abiOverride != null) {
7773            cpuAbiOverride = abiOverride;
7774        } else if (settings != null) {
7775            cpuAbiOverride = settings.cpuAbiOverrideString;
7776        }
7777
7778        return cpuAbiOverride;
7779    }
7780
7781    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7782            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7783                    throws PackageManagerException {
7784        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7785        // If the package has children and this is the first dive in the function
7786        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7787        // whether all packages (parent and children) would be successfully scanned
7788        // before the actual scan since scanning mutates internal state and we want
7789        // to atomically install the package and its children.
7790        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7791            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7792                scanFlags |= SCAN_CHECK_ONLY;
7793            }
7794        } else {
7795            scanFlags &= ~SCAN_CHECK_ONLY;
7796        }
7797
7798        final PackageParser.Package scannedPkg;
7799        try {
7800            // Scan the parent
7801            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7802            // Scan the children
7803            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7804            for (int i = 0; i < childCount; i++) {
7805                PackageParser.Package childPkg = pkg.childPackages.get(i);
7806                scanPackageLI(childPkg, policyFlags,
7807                        scanFlags, currentTime, user);
7808            }
7809        } finally {
7810            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7811        }
7812
7813        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7814            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7815        }
7816
7817        return scannedPkg;
7818    }
7819
7820    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7821            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7822        boolean success = false;
7823        try {
7824            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7825                    currentTime, user);
7826            success = true;
7827            return res;
7828        } finally {
7829            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7830                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7831                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7832                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7833                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7834            }
7835        }
7836    }
7837
7838    /**
7839     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7840     */
7841    private static boolean apkHasCode(String fileName) {
7842        StrictJarFile jarFile = null;
7843        try {
7844            jarFile = new StrictJarFile(fileName,
7845                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7846            return jarFile.findEntry("classes.dex") != null;
7847        } catch (IOException ignore) {
7848        } finally {
7849            try {
7850                if (jarFile != null) {
7851                    jarFile.close();
7852                }
7853            } catch (IOException ignore) {}
7854        }
7855        return false;
7856    }
7857
7858    /**
7859     * Enforces code policy for the package. This ensures that if an APK has
7860     * declared hasCode="true" in its manifest that the APK actually contains
7861     * code.
7862     *
7863     * @throws PackageManagerException If bytecode could not be found when it should exist
7864     */
7865    private static void enforceCodePolicy(PackageParser.Package pkg)
7866            throws PackageManagerException {
7867        final boolean shouldHaveCode =
7868                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7869        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7870            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7871                    "Package " + pkg.baseCodePath + " code is missing");
7872        }
7873
7874        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7875            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7876                final boolean splitShouldHaveCode =
7877                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7878                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7879                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7880                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7881                }
7882            }
7883        }
7884    }
7885
7886    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
7887            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
7888            throws PackageManagerException {
7889        final File scanFile = new File(pkg.codePath);
7890        if (pkg.applicationInfo.getCodePath() == null ||
7891                pkg.applicationInfo.getResourcePath() == null) {
7892            // Bail out. The resource and code paths haven't been set.
7893            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7894                    "Code and resource paths haven't been set correctly");
7895        }
7896
7897        // Apply policy
7898        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7899            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7900            if (pkg.applicationInfo.isDirectBootAware()) {
7901                // we're direct boot aware; set for all components
7902                for (PackageParser.Service s : pkg.services) {
7903                    s.info.encryptionAware = s.info.directBootAware = true;
7904                }
7905                for (PackageParser.Provider p : pkg.providers) {
7906                    p.info.encryptionAware = p.info.directBootAware = true;
7907                }
7908                for (PackageParser.Activity a : pkg.activities) {
7909                    a.info.encryptionAware = a.info.directBootAware = true;
7910                }
7911                for (PackageParser.Activity r : pkg.receivers) {
7912                    r.info.encryptionAware = r.info.directBootAware = true;
7913                }
7914            }
7915        } else {
7916            // Only allow system apps to be flagged as core apps.
7917            pkg.coreApp = false;
7918            // clear flags not applicable to regular apps
7919            pkg.applicationInfo.privateFlags &=
7920                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
7921            pkg.applicationInfo.privateFlags &=
7922                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
7923        }
7924        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
7925
7926        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7927            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7928        }
7929
7930        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
7931            enforceCodePolicy(pkg);
7932        }
7933
7934        if (mCustomResolverComponentName != null &&
7935                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7936            setUpCustomResolverActivity(pkg);
7937        }
7938
7939        if (pkg.packageName.equals("android")) {
7940            synchronized (mPackages) {
7941                if (mAndroidApplication != null) {
7942                    Slog.w(TAG, "*************************************************");
7943                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7944                    Slog.w(TAG, " file=" + scanFile);
7945                    Slog.w(TAG, "*************************************************");
7946                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7947                            "Core android package being redefined.  Skipping.");
7948                }
7949
7950                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7951                    // Set up information for our fall-back user intent resolution activity.
7952                    mPlatformPackage = pkg;
7953                    pkg.mVersionCode = mSdkVersion;
7954                    mAndroidApplication = pkg.applicationInfo;
7955
7956                    if (!mResolverReplaced) {
7957                        mResolveActivity.applicationInfo = mAndroidApplication;
7958                        mResolveActivity.name = ResolverActivity.class.getName();
7959                        mResolveActivity.packageName = mAndroidApplication.packageName;
7960                        mResolveActivity.processName = "system:ui";
7961                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7962                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7963                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7964                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
7965                        mResolveActivity.exported = true;
7966                        mResolveActivity.enabled = true;
7967                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
7968                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
7969                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
7970                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
7971                                | ActivityInfo.CONFIG_ORIENTATION
7972                                | ActivityInfo.CONFIG_KEYBOARD
7973                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
7974                        mResolveInfo.activityInfo = mResolveActivity;
7975                        mResolveInfo.priority = 0;
7976                        mResolveInfo.preferredOrder = 0;
7977                        mResolveInfo.match = 0;
7978                        mResolveComponentName = new ComponentName(
7979                                mAndroidApplication.packageName, mResolveActivity.name);
7980                    }
7981                }
7982            }
7983        }
7984
7985        if (DEBUG_PACKAGE_SCANNING) {
7986            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
7987                Log.d(TAG, "Scanning package " + pkg.packageName);
7988        }
7989
7990        synchronized (mPackages) {
7991            if (mPackages.containsKey(pkg.packageName)
7992                    || mSharedLibraries.containsKey(pkg.packageName)) {
7993                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7994                        "Application package " + pkg.packageName
7995                                + " already installed.  Skipping duplicate.");
7996            }
7997
7998            // If we're only installing presumed-existing packages, require that the
7999            // scanned APK is both already known and at the path previously established
8000            // for it.  Previously unknown packages we pick up normally, but if we have an
8001            // a priori expectation about this package's install presence, enforce it.
8002            // With a singular exception for new system packages. When an OTA contains
8003            // a new system package, we allow the codepath to change from a system location
8004            // to the user-installed location. If we don't allow this change, any newer,
8005            // user-installed version of the application will be ignored.
8006            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8007                if (mExpectingBetter.containsKey(pkg.packageName)) {
8008                    logCriticalInfo(Log.WARN,
8009                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8010                } else {
8011                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8012                    if (known != null) {
8013                        if (DEBUG_PACKAGE_SCANNING) {
8014                            Log.d(TAG, "Examining " + pkg.codePath
8015                                    + " and requiring known paths " + known.codePathString
8016                                    + " & " + known.resourcePathString);
8017                        }
8018                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8019                                || !pkg.applicationInfo.getResourcePath().equals(
8020                                known.resourcePathString)) {
8021                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8022                                    "Application package " + pkg.packageName
8023                                            + " found at " + pkg.applicationInfo.getCodePath()
8024                                            + " but expected at " + known.codePathString
8025                                            + "; ignoring.");
8026                        }
8027                    }
8028                }
8029            }
8030        }
8031
8032        // Initialize package source and resource directories
8033        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8034        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8035
8036        SharedUserSetting suid = null;
8037        PackageSetting pkgSetting = null;
8038
8039        if (!isSystemApp(pkg)) {
8040            // Only system apps can use these features.
8041            pkg.mOriginalPackages = null;
8042            pkg.mRealPackage = null;
8043            pkg.mAdoptPermissions = null;
8044        }
8045
8046        // Getting the package setting may have a side-effect, so if we
8047        // are only checking if scan would succeed, stash a copy of the
8048        // old setting to restore at the end.
8049        PackageSetting nonMutatedPs = null;
8050
8051        // writer
8052        synchronized (mPackages) {
8053            if (pkg.mSharedUserId != null) {
8054                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8055                if (suid == null) {
8056                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8057                            "Creating application package " + pkg.packageName
8058                            + " for shared user failed");
8059                }
8060                if (DEBUG_PACKAGE_SCANNING) {
8061                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8062                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8063                                + "): packages=" + suid.packages);
8064                }
8065            }
8066
8067            // Check if we are renaming from an original package name.
8068            PackageSetting origPackage = null;
8069            String realName = null;
8070            if (pkg.mOriginalPackages != null) {
8071                // This package may need to be renamed to a previously
8072                // installed name.  Let's check on that...
8073                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8074                if (pkg.mOriginalPackages.contains(renamed)) {
8075                    // This package had originally been installed as the
8076                    // original name, and we have already taken care of
8077                    // transitioning to the new one.  Just update the new
8078                    // one to continue using the old name.
8079                    realName = pkg.mRealPackage;
8080                    if (!pkg.packageName.equals(renamed)) {
8081                        // Callers into this function may have already taken
8082                        // care of renaming the package; only do it here if
8083                        // it is not already done.
8084                        pkg.setPackageName(renamed);
8085                    }
8086
8087                } else {
8088                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8089                        if ((origPackage = mSettings.peekPackageLPr(
8090                                pkg.mOriginalPackages.get(i))) != null) {
8091                            // We do have the package already installed under its
8092                            // original name...  should we use it?
8093                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8094                                // New package is not compatible with original.
8095                                origPackage = null;
8096                                continue;
8097                            } else if (origPackage.sharedUser != null) {
8098                                // Make sure uid is compatible between packages.
8099                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8100                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8101                                            + " to " + pkg.packageName + ": old uid "
8102                                            + origPackage.sharedUser.name
8103                                            + " differs from " + pkg.mSharedUserId);
8104                                    origPackage = null;
8105                                    continue;
8106                                }
8107                                // TODO: Add case when shared user id is added [b/28144775]
8108                            } else {
8109                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8110                                        + pkg.packageName + " to old name " + origPackage.name);
8111                            }
8112                            break;
8113                        }
8114                    }
8115                }
8116            }
8117
8118            if (mTransferedPackages.contains(pkg.packageName)) {
8119                Slog.w(TAG, "Package " + pkg.packageName
8120                        + " was transferred to another, but its .apk remains");
8121            }
8122
8123            // See comments in nonMutatedPs declaration
8124            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8125                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8126                if (foundPs != null) {
8127                    nonMutatedPs = new PackageSetting(foundPs);
8128                }
8129            }
8130
8131            // Just create the setting, don't add it yet. For already existing packages
8132            // the PkgSetting exists already and doesn't have to be created.
8133            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8134                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8135                    pkg.applicationInfo.primaryCpuAbi,
8136                    pkg.applicationInfo.secondaryCpuAbi,
8137                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8138                    user, false);
8139            if (pkgSetting == null) {
8140                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8141                        "Creating application package " + pkg.packageName + " failed");
8142            }
8143
8144            if (pkgSetting.origPackage != null) {
8145                // If we are first transitioning from an original package,
8146                // fix up the new package's name now.  We need to do this after
8147                // looking up the package under its new name, so getPackageLP
8148                // can take care of fiddling things correctly.
8149                pkg.setPackageName(origPackage.name);
8150
8151                // File a report about this.
8152                String msg = "New package " + pkgSetting.realName
8153                        + " renamed to replace old package " + pkgSetting.name;
8154                reportSettingsProblem(Log.WARN, msg);
8155
8156                // Make a note of it.
8157                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8158                    mTransferedPackages.add(origPackage.name);
8159                }
8160
8161                // No longer need to retain this.
8162                pkgSetting.origPackage = null;
8163            }
8164
8165            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8166                // Make a note of it.
8167                mTransferedPackages.add(pkg.packageName);
8168            }
8169
8170            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8171                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8172            }
8173
8174            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8175                // Check all shared libraries and map to their actual file path.
8176                // We only do this here for apps not on a system dir, because those
8177                // are the only ones that can fail an install due to this.  We
8178                // will take care of the system apps by updating all of their
8179                // library paths after the scan is done.
8180                updateSharedLibrariesLPw(pkg, null);
8181            }
8182
8183            if (mFoundPolicyFile) {
8184                SELinuxMMAC.assignSeinfoValue(pkg);
8185            }
8186
8187            pkg.applicationInfo.uid = pkgSetting.appId;
8188            pkg.mExtras = pkgSetting;
8189            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8190                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8191                    // We just determined the app is signed correctly, so bring
8192                    // over the latest parsed certs.
8193                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8194                } else {
8195                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8196                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8197                                "Package " + pkg.packageName + " upgrade keys do not match the "
8198                                + "previously installed version");
8199                    } else {
8200                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8201                        String msg = "System package " + pkg.packageName
8202                            + " signature changed; retaining data.";
8203                        reportSettingsProblem(Log.WARN, msg);
8204                    }
8205                }
8206            } else {
8207                try {
8208                    verifySignaturesLP(pkgSetting, pkg);
8209                    // We just determined the app is signed correctly, so bring
8210                    // over the latest parsed certs.
8211                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8212                } catch (PackageManagerException e) {
8213                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8214                        throw e;
8215                    }
8216                    // The signature has changed, but this package is in the system
8217                    // image...  let's recover!
8218                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8219                    // However...  if this package is part of a shared user, but it
8220                    // doesn't match the signature of the shared user, let's fail.
8221                    // What this means is that you can't change the signatures
8222                    // associated with an overall shared user, which doesn't seem all
8223                    // that unreasonable.
8224                    if (pkgSetting.sharedUser != null) {
8225                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8226                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8227                            throw new PackageManagerException(
8228                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8229                                            "Signature mismatch for shared user: "
8230                                            + pkgSetting.sharedUser);
8231                        }
8232                    }
8233                    // File a report about this.
8234                    String msg = "System package " + pkg.packageName
8235                        + " signature changed; retaining data.";
8236                    reportSettingsProblem(Log.WARN, msg);
8237                }
8238            }
8239            // Verify that this new package doesn't have any content providers
8240            // that conflict with existing packages.  Only do this if the
8241            // package isn't already installed, since we don't want to break
8242            // things that are installed.
8243            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8244                final int N = pkg.providers.size();
8245                int i;
8246                for (i=0; i<N; i++) {
8247                    PackageParser.Provider p = pkg.providers.get(i);
8248                    if (p.info.authority != null) {
8249                        String names[] = p.info.authority.split(";");
8250                        for (int j = 0; j < names.length; j++) {
8251                            if (mProvidersByAuthority.containsKey(names[j])) {
8252                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8253                                final String otherPackageName =
8254                                        ((other != null && other.getComponentName() != null) ?
8255                                                other.getComponentName().getPackageName() : "?");
8256                                throw new PackageManagerException(
8257                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8258                                                "Can't install because provider name " + names[j]
8259                                                + " (in package " + pkg.applicationInfo.packageName
8260                                                + ") is already used by " + otherPackageName);
8261                            }
8262                        }
8263                    }
8264                }
8265            }
8266
8267            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8268                // This package wants to adopt ownership of permissions from
8269                // another package.
8270                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8271                    final String origName = pkg.mAdoptPermissions.get(i);
8272                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8273                    if (orig != null) {
8274                        if (verifyPackageUpdateLPr(orig, pkg)) {
8275                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8276                                    + pkg.packageName);
8277                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8278                        }
8279                    }
8280                }
8281            }
8282        }
8283
8284        final String pkgName = pkg.packageName;
8285
8286        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
8287        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8288        pkg.applicationInfo.processName = fixProcessName(
8289                pkg.applicationInfo.packageName,
8290                pkg.applicationInfo.processName,
8291                pkg.applicationInfo.uid);
8292
8293        if (pkg != mPlatformPackage) {
8294            // Get all of our default paths setup
8295            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8296        }
8297
8298        final String path = scanFile.getPath();
8299        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8300
8301        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8302            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
8303            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /*extractLibs*/);
8304            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8305
8306            // Some system apps still use directory structure for native libraries
8307            // in which case we might end up not detecting abi solely based on apk
8308            // structure. Try to detect abi based on directory structure.
8309            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8310                    pkg.applicationInfo.primaryCpuAbi == null) {
8311                setBundledAppAbisAndRoots(pkg, pkgSetting);
8312                setNativeLibraryPaths(pkg);
8313            }
8314
8315        } else {
8316            if ((scanFlags & SCAN_MOVE) != 0) {
8317                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8318                // but we already have this packages package info in the PackageSetting. We just
8319                // use that and derive the native library path based on the new codepath.
8320                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8321                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8322            }
8323
8324            // Set native library paths again. For moves, the path will be updated based on the
8325            // ABIs we've determined above. For non-moves, the path will be updated based on the
8326            // ABIs we determined during compilation, but the path will depend on the final
8327            // package path (after the rename away from the stage path).
8328            setNativeLibraryPaths(pkg);
8329        }
8330
8331        // This is a special case for the "system" package, where the ABI is
8332        // dictated by the zygote configuration (and init.rc). We should keep track
8333        // of this ABI so that we can deal with "normal" applications that run under
8334        // the same UID correctly.
8335        if (mPlatformPackage == pkg) {
8336            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8337                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8338        }
8339
8340        // If there's a mismatch between the abi-override in the package setting
8341        // and the abiOverride specified for the install. Warn about this because we
8342        // would've already compiled the app without taking the package setting into
8343        // account.
8344        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8345            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8346                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8347                        " for package " + pkg.packageName);
8348            }
8349        }
8350
8351        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8352        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8353        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8354
8355        // Copy the derived override back to the parsed package, so that we can
8356        // update the package settings accordingly.
8357        pkg.cpuAbiOverride = cpuAbiOverride;
8358
8359        if (DEBUG_ABI_SELECTION) {
8360            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8361                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8362                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8363        }
8364
8365        // Push the derived path down into PackageSettings so we know what to
8366        // clean up at uninstall time.
8367        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8368
8369        if (DEBUG_ABI_SELECTION) {
8370            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8371                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8372                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8373        }
8374
8375        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8376            // We don't do this here during boot because we can do it all
8377            // at once after scanning all existing packages.
8378            //
8379            // We also do this *before* we perform dexopt on this package, so that
8380            // we can avoid redundant dexopts, and also to make sure we've got the
8381            // code and package path correct.
8382            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8383                    pkg, true /* boot complete */);
8384        }
8385
8386        if (mFactoryTest && pkg.requestedPermissions.contains(
8387                android.Manifest.permission.FACTORY_TEST)) {
8388            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8389        }
8390
8391        ArrayList<PackageParser.Package> clientLibPkgs = null;
8392
8393        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8394            if (nonMutatedPs != null) {
8395                synchronized (mPackages) {
8396                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8397                }
8398            }
8399            return pkg;
8400        }
8401
8402        // Only privileged apps and updated privileged apps can add child packages.
8403        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8404            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8405                throw new PackageManagerException("Only privileged apps and updated "
8406                        + "privileged apps can add child packages. Ignoring package "
8407                        + pkg.packageName);
8408            }
8409            final int childCount = pkg.childPackages.size();
8410            for (int i = 0; i < childCount; i++) {
8411                PackageParser.Package childPkg = pkg.childPackages.get(i);
8412                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8413                        childPkg.packageName)) {
8414                    throw new PackageManagerException("Cannot override a child package of "
8415                            + "another disabled system app. Ignoring package " + pkg.packageName);
8416                }
8417            }
8418        }
8419
8420        // writer
8421        synchronized (mPackages) {
8422            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8423                // Only system apps can add new shared libraries.
8424                if (pkg.libraryNames != null) {
8425                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8426                        String name = pkg.libraryNames.get(i);
8427                        boolean allowed = false;
8428                        if (pkg.isUpdatedSystemApp()) {
8429                            // New library entries can only be added through the
8430                            // system image.  This is important to get rid of a lot
8431                            // of nasty edge cases: for example if we allowed a non-
8432                            // system update of the app to add a library, then uninstalling
8433                            // the update would make the library go away, and assumptions
8434                            // we made such as through app install filtering would now
8435                            // have allowed apps on the device which aren't compatible
8436                            // with it.  Better to just have the restriction here, be
8437                            // conservative, and create many fewer cases that can negatively
8438                            // impact the user experience.
8439                            final PackageSetting sysPs = mSettings
8440                                    .getDisabledSystemPkgLPr(pkg.packageName);
8441                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8442                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8443                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8444                                        allowed = true;
8445                                        break;
8446                                    }
8447                                }
8448                            }
8449                        } else {
8450                            allowed = true;
8451                        }
8452                        if (allowed) {
8453                            if (!mSharedLibraries.containsKey(name)) {
8454                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8455                            } else if (!name.equals(pkg.packageName)) {
8456                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8457                                        + name + " already exists; skipping");
8458                            }
8459                        } else {
8460                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8461                                    + name + " that is not declared on system image; skipping");
8462                        }
8463                    }
8464                    if ((scanFlags & SCAN_BOOTING) == 0) {
8465                        // If we are not booting, we need to update any applications
8466                        // that are clients of our shared library.  If we are booting,
8467                        // this will all be done once the scan is complete.
8468                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8469                    }
8470                }
8471            }
8472        }
8473
8474        if ((scanFlags & SCAN_BOOTING) != 0) {
8475            // No apps can run during boot scan, so they don't need to be frozen
8476        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8477            // Caller asked to not kill app, so it's probably not frozen
8478        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8479            // Caller asked us to ignore frozen check for some reason; they
8480            // probably didn't know the package name
8481        } else {
8482            // We're doing major surgery on this package, so it better be frozen
8483            // right now to keep it from launching
8484            checkPackageFrozen(pkgName);
8485        }
8486
8487        // Also need to kill any apps that are dependent on the library.
8488        if (clientLibPkgs != null) {
8489            for (int i=0; i<clientLibPkgs.size(); i++) {
8490                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8491                killApplication(clientPkg.applicationInfo.packageName,
8492                        clientPkg.applicationInfo.uid, "update lib");
8493            }
8494        }
8495
8496        // Make sure we're not adding any bogus keyset info
8497        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8498        ksms.assertScannedPackageValid(pkg);
8499
8500        // writer
8501        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8502
8503        boolean createIdmapFailed = false;
8504        synchronized (mPackages) {
8505            // We don't expect installation to fail beyond this point
8506
8507            if (pkgSetting.pkg != null) {
8508                // Note that |user| might be null during the initial boot scan. If a codePath
8509                // for an app has changed during a boot scan, it's due to an app update that's
8510                // part of the system partition and marker changes must be applied to all users.
8511                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8512                    (user != null) ? user : UserHandle.ALL);
8513            }
8514
8515            // Add the new setting to mSettings
8516            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8517            // Add the new setting to mPackages
8518            mPackages.put(pkg.applicationInfo.packageName, pkg);
8519            // Make sure we don't accidentally delete its data.
8520            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8521            while (iter.hasNext()) {
8522                PackageCleanItem item = iter.next();
8523                if (pkgName.equals(item.packageName)) {
8524                    iter.remove();
8525                }
8526            }
8527
8528            // Take care of first install / last update times.
8529            if (currentTime != 0) {
8530                if (pkgSetting.firstInstallTime == 0) {
8531                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8532                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8533                    pkgSetting.lastUpdateTime = currentTime;
8534                }
8535            } else if (pkgSetting.firstInstallTime == 0) {
8536                // We need *something*.  Take time time stamp of the file.
8537                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8538            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8539                if (scanFileTime != pkgSetting.timeStamp) {
8540                    // A package on the system image has changed; consider this
8541                    // to be an update.
8542                    pkgSetting.lastUpdateTime = scanFileTime;
8543                }
8544            }
8545
8546            // Add the package's KeySets to the global KeySetManagerService
8547            ksms.addScannedPackageLPw(pkg);
8548
8549            int N = pkg.providers.size();
8550            StringBuilder r = null;
8551            int i;
8552            for (i=0; i<N; i++) {
8553                PackageParser.Provider p = pkg.providers.get(i);
8554                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8555                        p.info.processName, pkg.applicationInfo.uid);
8556                mProviders.addProvider(p);
8557                p.syncable = p.info.isSyncable;
8558                if (p.info.authority != null) {
8559                    String names[] = p.info.authority.split(";");
8560                    p.info.authority = null;
8561                    for (int j = 0; j < names.length; j++) {
8562                        if (j == 1 && p.syncable) {
8563                            // We only want the first authority for a provider to possibly be
8564                            // syncable, so if we already added this provider using a different
8565                            // authority clear the syncable flag. We copy the provider before
8566                            // changing it because the mProviders object contains a reference
8567                            // to a provider that we don't want to change.
8568                            // Only do this for the second authority since the resulting provider
8569                            // object can be the same for all future authorities for this provider.
8570                            p = new PackageParser.Provider(p);
8571                            p.syncable = false;
8572                        }
8573                        if (!mProvidersByAuthority.containsKey(names[j])) {
8574                            mProvidersByAuthority.put(names[j], p);
8575                            if (p.info.authority == null) {
8576                                p.info.authority = names[j];
8577                            } else {
8578                                p.info.authority = p.info.authority + ";" + names[j];
8579                            }
8580                            if (DEBUG_PACKAGE_SCANNING) {
8581                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8582                                    Log.d(TAG, "Registered content provider: " + names[j]
8583                                            + ", className = " + p.info.name + ", isSyncable = "
8584                                            + p.info.isSyncable);
8585                            }
8586                        } else {
8587                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8588                            Slog.w(TAG, "Skipping provider name " + names[j] +
8589                                    " (in package " + pkg.applicationInfo.packageName +
8590                                    "): name already used by "
8591                                    + ((other != null && other.getComponentName() != null)
8592                                            ? other.getComponentName().getPackageName() : "?"));
8593                        }
8594                    }
8595                }
8596                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8597                    if (r == null) {
8598                        r = new StringBuilder(256);
8599                    } else {
8600                        r.append(' ');
8601                    }
8602                    r.append(p.info.name);
8603                }
8604            }
8605            if (r != null) {
8606                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8607            }
8608
8609            N = pkg.services.size();
8610            r = null;
8611            for (i=0; i<N; i++) {
8612                PackageParser.Service s = pkg.services.get(i);
8613                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8614                        s.info.processName, pkg.applicationInfo.uid);
8615                mServices.addService(s);
8616                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8617                    if (r == null) {
8618                        r = new StringBuilder(256);
8619                    } else {
8620                        r.append(' ');
8621                    }
8622                    r.append(s.info.name);
8623                }
8624            }
8625            if (r != null) {
8626                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8627            }
8628
8629            N = pkg.receivers.size();
8630            r = null;
8631            for (i=0; i<N; i++) {
8632                PackageParser.Activity a = pkg.receivers.get(i);
8633                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8634                        a.info.processName, pkg.applicationInfo.uid);
8635                mReceivers.addActivity(a, "receiver");
8636                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8637                    if (r == null) {
8638                        r = new StringBuilder(256);
8639                    } else {
8640                        r.append(' ');
8641                    }
8642                    r.append(a.info.name);
8643                }
8644            }
8645            if (r != null) {
8646                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8647            }
8648
8649            N = pkg.activities.size();
8650            r = null;
8651            for (i=0; i<N; i++) {
8652                PackageParser.Activity a = pkg.activities.get(i);
8653                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8654                        a.info.processName, pkg.applicationInfo.uid);
8655                mActivities.addActivity(a, "activity");
8656                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8657                    if (r == null) {
8658                        r = new StringBuilder(256);
8659                    } else {
8660                        r.append(' ');
8661                    }
8662                    r.append(a.info.name);
8663                }
8664            }
8665            if (r != null) {
8666                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8667            }
8668
8669            N = pkg.permissionGroups.size();
8670            r = null;
8671            for (i=0; i<N; i++) {
8672                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8673                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8674                if (cur == null) {
8675                    mPermissionGroups.put(pg.info.name, pg);
8676                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8677                        if (r == null) {
8678                            r = new StringBuilder(256);
8679                        } else {
8680                            r.append(' ');
8681                        }
8682                        r.append(pg.info.name);
8683                    }
8684                } else {
8685                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8686                            + pg.info.packageName + " ignored: original from "
8687                            + cur.info.packageName);
8688                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8689                        if (r == null) {
8690                            r = new StringBuilder(256);
8691                        } else {
8692                            r.append(' ');
8693                        }
8694                        r.append("DUP:");
8695                        r.append(pg.info.name);
8696                    }
8697                }
8698            }
8699            if (r != null) {
8700                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8701            }
8702
8703            N = pkg.permissions.size();
8704            r = null;
8705            for (i=0; i<N; i++) {
8706                PackageParser.Permission p = pkg.permissions.get(i);
8707
8708                // Assume by default that we did not install this permission into the system.
8709                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8710
8711                // Now that permission groups have a special meaning, we ignore permission
8712                // groups for legacy apps to prevent unexpected behavior. In particular,
8713                // permissions for one app being granted to someone just becase they happen
8714                // to be in a group defined by another app (before this had no implications).
8715                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8716                    p.group = mPermissionGroups.get(p.info.group);
8717                    // Warn for a permission in an unknown group.
8718                    if (p.info.group != null && p.group == null) {
8719                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8720                                + p.info.packageName + " in an unknown group " + p.info.group);
8721                    }
8722                }
8723
8724                ArrayMap<String, BasePermission> permissionMap =
8725                        p.tree ? mSettings.mPermissionTrees
8726                                : mSettings.mPermissions;
8727                BasePermission bp = permissionMap.get(p.info.name);
8728
8729                // Allow system apps to redefine non-system permissions
8730                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8731                    final boolean currentOwnerIsSystem = (bp.perm != null
8732                            && isSystemApp(bp.perm.owner));
8733                    if (isSystemApp(p.owner)) {
8734                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8735                            // It's a built-in permission and no owner, take ownership now
8736                            bp.packageSetting = pkgSetting;
8737                            bp.perm = p;
8738                            bp.uid = pkg.applicationInfo.uid;
8739                            bp.sourcePackage = p.info.packageName;
8740                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8741                        } else if (!currentOwnerIsSystem) {
8742                            String msg = "New decl " + p.owner + " of permission  "
8743                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8744                            reportSettingsProblem(Log.WARN, msg);
8745                            bp = null;
8746                        }
8747                    }
8748                }
8749
8750                if (bp == null) {
8751                    bp = new BasePermission(p.info.name, p.info.packageName,
8752                            BasePermission.TYPE_NORMAL);
8753                    permissionMap.put(p.info.name, bp);
8754                }
8755
8756                if (bp.perm == null) {
8757                    if (bp.sourcePackage == null
8758                            || bp.sourcePackage.equals(p.info.packageName)) {
8759                        BasePermission tree = findPermissionTreeLP(p.info.name);
8760                        if (tree == null
8761                                || tree.sourcePackage.equals(p.info.packageName)) {
8762                            bp.packageSetting = pkgSetting;
8763                            bp.perm = p;
8764                            bp.uid = pkg.applicationInfo.uid;
8765                            bp.sourcePackage = p.info.packageName;
8766                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8767                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8768                                if (r == null) {
8769                                    r = new StringBuilder(256);
8770                                } else {
8771                                    r.append(' ');
8772                                }
8773                                r.append(p.info.name);
8774                            }
8775                        } else {
8776                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8777                                    + p.info.packageName + " ignored: base tree "
8778                                    + tree.name + " is from package "
8779                                    + tree.sourcePackage);
8780                        }
8781                    } else {
8782                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8783                                + p.info.packageName + " ignored: original from "
8784                                + bp.sourcePackage);
8785                    }
8786                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8787                    if (r == null) {
8788                        r = new StringBuilder(256);
8789                    } else {
8790                        r.append(' ');
8791                    }
8792                    r.append("DUP:");
8793                    r.append(p.info.name);
8794                }
8795                if (bp.perm == p) {
8796                    bp.protectionLevel = p.info.protectionLevel;
8797                }
8798            }
8799
8800            if (r != null) {
8801                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8802            }
8803
8804            N = pkg.instrumentation.size();
8805            r = null;
8806            for (i=0; i<N; i++) {
8807                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8808                a.info.packageName = pkg.applicationInfo.packageName;
8809                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8810                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8811                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8812                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8813                a.info.dataDir = pkg.applicationInfo.dataDir;
8814                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8815                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8816
8817                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8818                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8819                mInstrumentation.put(a.getComponentName(), a);
8820                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8821                    if (r == null) {
8822                        r = new StringBuilder(256);
8823                    } else {
8824                        r.append(' ');
8825                    }
8826                    r.append(a.info.name);
8827                }
8828            }
8829            if (r != null) {
8830                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8831            }
8832
8833            if (pkg.protectedBroadcasts != null) {
8834                N = pkg.protectedBroadcasts.size();
8835                for (i=0; i<N; i++) {
8836                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8837                }
8838            }
8839
8840            pkgSetting.setTimeStamp(scanFileTime);
8841
8842            // Create idmap files for pairs of (packages, overlay packages).
8843            // Note: "android", ie framework-res.apk, is handled by native layers.
8844            if (pkg.mOverlayTarget != null) {
8845                // This is an overlay package.
8846                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8847                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8848                        mOverlays.put(pkg.mOverlayTarget,
8849                                new ArrayMap<String, PackageParser.Package>());
8850                    }
8851                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8852                    map.put(pkg.packageName, pkg);
8853                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8854                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8855                        createIdmapFailed = true;
8856                    }
8857                }
8858            } else if (mOverlays.containsKey(pkg.packageName) &&
8859                    !pkg.packageName.equals("android")) {
8860                // This is a regular package, with one or more known overlay packages.
8861                createIdmapsForPackageLI(pkg);
8862            }
8863        }
8864
8865        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8866
8867        if (createIdmapFailed) {
8868            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8869                    "scanPackageLI failed to createIdmap");
8870        }
8871        return pkg;
8872    }
8873
8874    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
8875            PackageParser.Package update, UserHandle user) {
8876        if (existing.applicationInfo == null || update.applicationInfo == null) {
8877            // This isn't due to an app installation.
8878            return;
8879        }
8880
8881        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
8882        final File newCodePath = new File(update.applicationInfo.getCodePath());
8883
8884        // The codePath hasn't changed, so there's nothing for us to do.
8885        if (Objects.equals(oldCodePath, newCodePath)) {
8886            return;
8887        }
8888
8889        File canonicalNewCodePath;
8890        try {
8891            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
8892        } catch (IOException e) {
8893            Slog.w(TAG, "Failed to get canonical path.", e);
8894            return;
8895        }
8896
8897        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
8898        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
8899        // that the last component of the path (i.e, the name) doesn't need canonicalization
8900        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
8901        // but may change in the future. Hopefully this function won't exist at that point.
8902        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
8903                oldCodePath.getName());
8904
8905        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
8906        // with "@".
8907        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
8908        if (!oldMarkerPrefix.endsWith("@")) {
8909            oldMarkerPrefix += "@";
8910        }
8911        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
8912        if (!newMarkerPrefix.endsWith("@")) {
8913            newMarkerPrefix += "@";
8914        }
8915
8916        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
8917        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
8918        for (String updatedPath : updatedPaths) {
8919            String updatedPathName = new File(updatedPath).getName();
8920            markerSuffixes.add(updatedPathName.replace('/', '@'));
8921        }
8922
8923        for (int userId : resolveUserIds(user.getIdentifier())) {
8924            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
8925
8926            for (String markerSuffix : markerSuffixes) {
8927                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
8928                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
8929                if (oldForeignUseMark.exists()) {
8930                    try {
8931                        Os.rename(oldForeignUseMark.getAbsolutePath(),
8932                                newForeignUseMark.getAbsolutePath());
8933                    } catch (ErrnoException e) {
8934                        Slog.w(TAG, "Failed to rename foreign use marker", e);
8935                        oldForeignUseMark.delete();
8936                    }
8937                }
8938            }
8939        }
8940    }
8941
8942    /**
8943     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8944     * is derived purely on the basis of the contents of {@code scanFile} and
8945     * {@code cpuAbiOverride}.
8946     *
8947     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8948     */
8949    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8950                                 String cpuAbiOverride, boolean extractLibs)
8951            throws PackageManagerException {
8952        // TODO: We can probably be smarter about this stuff. For installed apps,
8953        // we can calculate this information at install time once and for all. For
8954        // system apps, we can probably assume that this information doesn't change
8955        // after the first boot scan. As things stand, we do lots of unnecessary work.
8956
8957        // Give ourselves some initial paths; we'll come back for another
8958        // pass once we've determined ABI below.
8959        setNativeLibraryPaths(pkg);
8960
8961        // We would never need to extract libs for forward-locked and external packages,
8962        // since the container service will do it for us. We shouldn't attempt to
8963        // extract libs from system app when it was not updated.
8964        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8965                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8966            extractLibs = false;
8967        }
8968
8969        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8970        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8971
8972        NativeLibraryHelper.Handle handle = null;
8973        try {
8974            handle = NativeLibraryHelper.Handle.create(pkg);
8975            // TODO(multiArch): This can be null for apps that didn't go through the
8976            // usual installation process. We can calculate it again, like we
8977            // do during install time.
8978            //
8979            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8980            // unnecessary.
8981            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8982
8983            // Null out the abis so that they can be recalculated.
8984            pkg.applicationInfo.primaryCpuAbi = null;
8985            pkg.applicationInfo.secondaryCpuAbi = null;
8986            if (isMultiArch(pkg.applicationInfo)) {
8987                // Warn if we've set an abiOverride for multi-lib packages..
8988                // By definition, we need to copy both 32 and 64 bit libraries for
8989                // such packages.
8990                if (pkg.cpuAbiOverride != null
8991                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8992                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8993                }
8994
8995                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8996                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8997                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8998                    if (extractLibs) {
8999                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9000                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9001                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9002                                useIsaSpecificSubdirs);
9003                    } else {
9004                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9005                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9006                    }
9007                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9008                }
9009
9010                maybeThrowExceptionForMultiArchCopy(
9011                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9012
9013                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9014                    if (extractLibs) {
9015                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9016                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9017                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9018                                useIsaSpecificSubdirs);
9019                    } else {
9020                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9021                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9022                    }
9023                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9024                }
9025
9026                maybeThrowExceptionForMultiArchCopy(
9027                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9028
9029                if (abi64 >= 0) {
9030                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9031                }
9032
9033                if (abi32 >= 0) {
9034                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9035                    if (abi64 >= 0) {
9036                        if (pkg.use32bitAbi) {
9037                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9038                            pkg.applicationInfo.primaryCpuAbi = abi;
9039                        } else {
9040                            pkg.applicationInfo.secondaryCpuAbi = abi;
9041                        }
9042                    } else {
9043                        pkg.applicationInfo.primaryCpuAbi = abi;
9044                    }
9045                }
9046
9047            } else {
9048                String[] abiList = (cpuAbiOverride != null) ?
9049                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9050
9051                // Enable gross and lame hacks for apps that are built with old
9052                // SDK tools. We must scan their APKs for renderscript bitcode and
9053                // not launch them if it's present. Don't bother checking on devices
9054                // that don't have 64 bit support.
9055                boolean needsRenderScriptOverride = false;
9056                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9057                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9058                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9059                    needsRenderScriptOverride = true;
9060                }
9061
9062                final int copyRet;
9063                if (extractLibs) {
9064                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
9065                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9066                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9067                } else {
9068                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
9069                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9070                }
9071                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9072
9073                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9074                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9075                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9076                }
9077
9078                if (copyRet >= 0) {
9079                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9080                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9081                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9082                } else if (needsRenderScriptOverride) {
9083                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9084                }
9085            }
9086        } catch (IOException ioe) {
9087            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9088        } finally {
9089            IoUtils.closeQuietly(handle);
9090        }
9091
9092        // Now that we've calculated the ABIs and determined if it's an internal app,
9093        // we will go ahead and populate the nativeLibraryPath.
9094        setNativeLibraryPaths(pkg);
9095    }
9096
9097    /**
9098     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9099     * i.e, so that all packages can be run inside a single process if required.
9100     *
9101     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9102     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9103     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9104     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9105     * updating a package that belongs to a shared user.
9106     *
9107     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9108     * adds unnecessary complexity.
9109     */
9110    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9111            PackageParser.Package scannedPackage, boolean bootComplete) {
9112        String requiredInstructionSet = null;
9113        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9114            requiredInstructionSet = VMRuntime.getInstructionSet(
9115                     scannedPackage.applicationInfo.primaryCpuAbi);
9116        }
9117
9118        PackageSetting requirer = null;
9119        for (PackageSetting ps : packagesForUser) {
9120            // If packagesForUser contains scannedPackage, we skip it. This will happen
9121            // when scannedPackage is an update of an existing package. Without this check,
9122            // we will never be able to change the ABI of any package belonging to a shared
9123            // user, even if it's compatible with other packages.
9124            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9125                if (ps.primaryCpuAbiString == null) {
9126                    continue;
9127                }
9128
9129                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9130                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9131                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9132                    // this but there's not much we can do.
9133                    String errorMessage = "Instruction set mismatch, "
9134                            + ((requirer == null) ? "[caller]" : requirer)
9135                            + " requires " + requiredInstructionSet + " whereas " + ps
9136                            + " requires " + instructionSet;
9137                    Slog.w(TAG, errorMessage);
9138                }
9139
9140                if (requiredInstructionSet == null) {
9141                    requiredInstructionSet = instructionSet;
9142                    requirer = ps;
9143                }
9144            }
9145        }
9146
9147        if (requiredInstructionSet != null) {
9148            String adjustedAbi;
9149            if (requirer != null) {
9150                // requirer != null implies that either scannedPackage was null or that scannedPackage
9151                // did not require an ABI, in which case we have to adjust scannedPackage to match
9152                // the ABI of the set (which is the same as requirer's ABI)
9153                adjustedAbi = requirer.primaryCpuAbiString;
9154                if (scannedPackage != null) {
9155                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9156                }
9157            } else {
9158                // requirer == null implies that we're updating all ABIs in the set to
9159                // match scannedPackage.
9160                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9161            }
9162
9163            for (PackageSetting ps : packagesForUser) {
9164                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9165                    if (ps.primaryCpuAbiString != null) {
9166                        continue;
9167                    }
9168
9169                    ps.primaryCpuAbiString = adjustedAbi;
9170                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9171                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9172                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9173                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9174                                + " (requirer="
9175                                + (requirer == null ? "null" : requirer.pkg.packageName)
9176                                + ", scannedPackage="
9177                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9178                                + ")");
9179                        try {
9180                            mInstaller.rmdex(ps.codePathString,
9181                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9182                        } catch (InstallerException ignored) {
9183                        }
9184                    }
9185                }
9186            }
9187        }
9188    }
9189
9190    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9191        synchronized (mPackages) {
9192            mResolverReplaced = true;
9193            // Set up information for custom user intent resolution activity.
9194            mResolveActivity.applicationInfo = pkg.applicationInfo;
9195            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9196            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9197            mResolveActivity.processName = pkg.applicationInfo.packageName;
9198            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9199            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9200                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9201            mResolveActivity.theme = 0;
9202            mResolveActivity.exported = true;
9203            mResolveActivity.enabled = true;
9204            mResolveInfo.activityInfo = mResolveActivity;
9205            mResolveInfo.priority = 0;
9206            mResolveInfo.preferredOrder = 0;
9207            mResolveInfo.match = 0;
9208            mResolveComponentName = mCustomResolverComponentName;
9209            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9210                    mResolveComponentName);
9211        }
9212    }
9213
9214    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9215        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9216
9217        // Set up information for ephemeral installer activity
9218        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9219        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9220        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9221        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9222        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9223        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9224                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9225        mEphemeralInstallerActivity.theme = 0;
9226        mEphemeralInstallerActivity.exported = true;
9227        mEphemeralInstallerActivity.enabled = true;
9228        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9229        mEphemeralInstallerInfo.priority = 0;
9230        mEphemeralInstallerInfo.preferredOrder = 0;
9231        mEphemeralInstallerInfo.match = 0;
9232
9233        if (DEBUG_EPHEMERAL) {
9234            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9235        }
9236    }
9237
9238    private static String calculateBundledApkRoot(final String codePathString) {
9239        final File codePath = new File(codePathString);
9240        final File codeRoot;
9241        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9242            codeRoot = Environment.getRootDirectory();
9243        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9244            codeRoot = Environment.getOemDirectory();
9245        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9246            codeRoot = Environment.getVendorDirectory();
9247        } else {
9248            // Unrecognized code path; take its top real segment as the apk root:
9249            // e.g. /something/app/blah.apk => /something
9250            try {
9251                File f = codePath.getCanonicalFile();
9252                File parent = f.getParentFile();    // non-null because codePath is a file
9253                File tmp;
9254                while ((tmp = parent.getParentFile()) != null) {
9255                    f = parent;
9256                    parent = tmp;
9257                }
9258                codeRoot = f;
9259                Slog.w(TAG, "Unrecognized code path "
9260                        + codePath + " - using " + codeRoot);
9261            } catch (IOException e) {
9262                // Can't canonicalize the code path -- shenanigans?
9263                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9264                return Environment.getRootDirectory().getPath();
9265            }
9266        }
9267        return codeRoot.getPath();
9268    }
9269
9270    /**
9271     * Derive and set the location of native libraries for the given package,
9272     * which varies depending on where and how the package was installed.
9273     */
9274    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9275        final ApplicationInfo info = pkg.applicationInfo;
9276        final String codePath = pkg.codePath;
9277        final File codeFile = new File(codePath);
9278        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9279        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9280
9281        info.nativeLibraryRootDir = null;
9282        info.nativeLibraryRootRequiresIsa = false;
9283        info.nativeLibraryDir = null;
9284        info.secondaryNativeLibraryDir = null;
9285
9286        if (isApkFile(codeFile)) {
9287            // Monolithic install
9288            if (bundledApp) {
9289                // If "/system/lib64/apkname" exists, assume that is the per-package
9290                // native library directory to use; otherwise use "/system/lib/apkname".
9291                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9292                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9293                        getPrimaryInstructionSet(info));
9294
9295                // This is a bundled system app so choose the path based on the ABI.
9296                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9297                // is just the default path.
9298                final String apkName = deriveCodePathName(codePath);
9299                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9300                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9301                        apkName).getAbsolutePath();
9302
9303                if (info.secondaryCpuAbi != null) {
9304                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9305                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9306                            secondaryLibDir, apkName).getAbsolutePath();
9307                }
9308            } else if (asecApp) {
9309                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9310                        .getAbsolutePath();
9311            } else {
9312                final String apkName = deriveCodePathName(codePath);
9313                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9314                        .getAbsolutePath();
9315            }
9316
9317            info.nativeLibraryRootRequiresIsa = false;
9318            info.nativeLibraryDir = info.nativeLibraryRootDir;
9319        } else {
9320            // Cluster install
9321            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9322            info.nativeLibraryRootRequiresIsa = true;
9323
9324            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9325                    getPrimaryInstructionSet(info)).getAbsolutePath();
9326
9327            if (info.secondaryCpuAbi != null) {
9328                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9329                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9330            }
9331        }
9332    }
9333
9334    /**
9335     * Calculate the abis and roots for a bundled app. These can uniquely
9336     * be determined from the contents of the system partition, i.e whether
9337     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9338     * of this information, and instead assume that the system was built
9339     * sensibly.
9340     */
9341    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9342                                           PackageSetting pkgSetting) {
9343        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9344
9345        // If "/system/lib64/apkname" exists, assume that is the per-package
9346        // native library directory to use; otherwise use "/system/lib/apkname".
9347        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9348        setBundledAppAbi(pkg, apkRoot, apkName);
9349        // pkgSetting might be null during rescan following uninstall of updates
9350        // to a bundled app, so accommodate that possibility.  The settings in
9351        // that case will be established later from the parsed package.
9352        //
9353        // If the settings aren't null, sync them up with what we've just derived.
9354        // note that apkRoot isn't stored in the package settings.
9355        if (pkgSetting != null) {
9356            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9357            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9358        }
9359    }
9360
9361    /**
9362     * Deduces the ABI of a bundled app and sets the relevant fields on the
9363     * parsed pkg object.
9364     *
9365     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9366     *        under which system libraries are installed.
9367     * @param apkName the name of the installed package.
9368     */
9369    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9370        final File codeFile = new File(pkg.codePath);
9371
9372        final boolean has64BitLibs;
9373        final boolean has32BitLibs;
9374        if (isApkFile(codeFile)) {
9375            // Monolithic install
9376            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9377            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9378        } else {
9379            // Cluster install
9380            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9381            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9382                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9383                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9384                has64BitLibs = (new File(rootDir, isa)).exists();
9385            } else {
9386                has64BitLibs = false;
9387            }
9388            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9389                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9390                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9391                has32BitLibs = (new File(rootDir, isa)).exists();
9392            } else {
9393                has32BitLibs = false;
9394            }
9395        }
9396
9397        if (has64BitLibs && !has32BitLibs) {
9398            // The package has 64 bit libs, but not 32 bit libs. Its primary
9399            // ABI should be 64 bit. We can safely assume here that the bundled
9400            // native libraries correspond to the most preferred ABI in the list.
9401
9402            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9403            pkg.applicationInfo.secondaryCpuAbi = null;
9404        } else if (has32BitLibs && !has64BitLibs) {
9405            // The package has 32 bit libs but not 64 bit libs. Its primary
9406            // ABI should be 32 bit.
9407
9408            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9409            pkg.applicationInfo.secondaryCpuAbi = null;
9410        } else if (has32BitLibs && has64BitLibs) {
9411            // The application has both 64 and 32 bit bundled libraries. We check
9412            // here that the app declares multiArch support, and warn if it doesn't.
9413            //
9414            // We will be lenient here and record both ABIs. The primary will be the
9415            // ABI that's higher on the list, i.e, a device that's configured to prefer
9416            // 64 bit apps will see a 64 bit primary ABI,
9417
9418            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9419                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9420            }
9421
9422            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9423                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9424                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9425            } else {
9426                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9427                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9428            }
9429        } else {
9430            pkg.applicationInfo.primaryCpuAbi = null;
9431            pkg.applicationInfo.secondaryCpuAbi = null;
9432        }
9433    }
9434
9435    private void killApplication(String pkgName, int appId, String reason) {
9436        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
9437    }
9438
9439    private void killApplication(String pkgName, int appId, int userId, String reason) {
9440        // Request the ActivityManager to kill the process(only for existing packages)
9441        // so that we do not end up in a confused state while the user is still using the older
9442        // version of the application while the new one gets installed.
9443        final long token = Binder.clearCallingIdentity();
9444        try {
9445            IActivityManager am = ActivityManagerNative.getDefault();
9446            if (am != null) {
9447                try {
9448                    am.killApplication(pkgName, appId, userId, reason);
9449                } catch (RemoteException e) {
9450                }
9451            }
9452        } finally {
9453            Binder.restoreCallingIdentity(token);
9454        }
9455    }
9456
9457    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9458        // Remove the parent package setting
9459        PackageSetting ps = (PackageSetting) pkg.mExtras;
9460        if (ps != null) {
9461            removePackageLI(ps, chatty);
9462        }
9463        // Remove the child package setting
9464        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9465        for (int i = 0; i < childCount; i++) {
9466            PackageParser.Package childPkg = pkg.childPackages.get(i);
9467            ps = (PackageSetting) childPkg.mExtras;
9468            if (ps != null) {
9469                removePackageLI(ps, chatty);
9470            }
9471        }
9472    }
9473
9474    void removePackageLI(PackageSetting ps, boolean chatty) {
9475        if (DEBUG_INSTALL) {
9476            if (chatty)
9477                Log.d(TAG, "Removing package " + ps.name);
9478        }
9479
9480        // writer
9481        synchronized (mPackages) {
9482            mPackages.remove(ps.name);
9483            final PackageParser.Package pkg = ps.pkg;
9484            if (pkg != null) {
9485                cleanPackageDataStructuresLILPw(pkg, chatty);
9486            }
9487        }
9488    }
9489
9490    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9491        if (DEBUG_INSTALL) {
9492            if (chatty)
9493                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9494        }
9495
9496        // writer
9497        synchronized (mPackages) {
9498            // Remove the parent package
9499            mPackages.remove(pkg.applicationInfo.packageName);
9500            cleanPackageDataStructuresLILPw(pkg, chatty);
9501
9502            // Remove the child packages
9503            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9504            for (int i = 0; i < childCount; i++) {
9505                PackageParser.Package childPkg = pkg.childPackages.get(i);
9506                mPackages.remove(childPkg.applicationInfo.packageName);
9507                cleanPackageDataStructuresLILPw(childPkg, chatty);
9508            }
9509        }
9510    }
9511
9512    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9513        int N = pkg.providers.size();
9514        StringBuilder r = null;
9515        int i;
9516        for (i=0; i<N; i++) {
9517            PackageParser.Provider p = pkg.providers.get(i);
9518            mProviders.removeProvider(p);
9519            if (p.info.authority == null) {
9520
9521                /* There was another ContentProvider with this authority when
9522                 * this app was installed so this authority is null,
9523                 * Ignore it as we don't have to unregister the provider.
9524                 */
9525                continue;
9526            }
9527            String names[] = p.info.authority.split(";");
9528            for (int j = 0; j < names.length; j++) {
9529                if (mProvidersByAuthority.get(names[j]) == p) {
9530                    mProvidersByAuthority.remove(names[j]);
9531                    if (DEBUG_REMOVE) {
9532                        if (chatty)
9533                            Log.d(TAG, "Unregistered content provider: " + names[j]
9534                                    + ", className = " + p.info.name + ", isSyncable = "
9535                                    + p.info.isSyncable);
9536                    }
9537                }
9538            }
9539            if (DEBUG_REMOVE && chatty) {
9540                if (r == null) {
9541                    r = new StringBuilder(256);
9542                } else {
9543                    r.append(' ');
9544                }
9545                r.append(p.info.name);
9546            }
9547        }
9548        if (r != null) {
9549            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9550        }
9551
9552        N = pkg.services.size();
9553        r = null;
9554        for (i=0; i<N; i++) {
9555            PackageParser.Service s = pkg.services.get(i);
9556            mServices.removeService(s);
9557            if (chatty) {
9558                if (r == null) {
9559                    r = new StringBuilder(256);
9560                } else {
9561                    r.append(' ');
9562                }
9563                r.append(s.info.name);
9564            }
9565        }
9566        if (r != null) {
9567            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9568        }
9569
9570        N = pkg.receivers.size();
9571        r = null;
9572        for (i=0; i<N; i++) {
9573            PackageParser.Activity a = pkg.receivers.get(i);
9574            mReceivers.removeActivity(a, "receiver");
9575            if (DEBUG_REMOVE && chatty) {
9576                if (r == null) {
9577                    r = new StringBuilder(256);
9578                } else {
9579                    r.append(' ');
9580                }
9581                r.append(a.info.name);
9582            }
9583        }
9584        if (r != null) {
9585            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9586        }
9587
9588        N = pkg.activities.size();
9589        r = null;
9590        for (i=0; i<N; i++) {
9591            PackageParser.Activity a = pkg.activities.get(i);
9592            mActivities.removeActivity(a, "activity");
9593            if (DEBUG_REMOVE && chatty) {
9594                if (r == null) {
9595                    r = new StringBuilder(256);
9596                } else {
9597                    r.append(' ');
9598                }
9599                r.append(a.info.name);
9600            }
9601        }
9602        if (r != null) {
9603            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9604        }
9605
9606        N = pkg.permissions.size();
9607        r = null;
9608        for (i=0; i<N; i++) {
9609            PackageParser.Permission p = pkg.permissions.get(i);
9610            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9611            if (bp == null) {
9612                bp = mSettings.mPermissionTrees.get(p.info.name);
9613            }
9614            if (bp != null && bp.perm == p) {
9615                bp.perm = null;
9616                if (DEBUG_REMOVE && chatty) {
9617                    if (r == null) {
9618                        r = new StringBuilder(256);
9619                    } else {
9620                        r.append(' ');
9621                    }
9622                    r.append(p.info.name);
9623                }
9624            }
9625            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9626                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9627                if (appOpPkgs != null) {
9628                    appOpPkgs.remove(pkg.packageName);
9629                }
9630            }
9631        }
9632        if (r != null) {
9633            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9634        }
9635
9636        N = pkg.requestedPermissions.size();
9637        r = null;
9638        for (i=0; i<N; i++) {
9639            String perm = pkg.requestedPermissions.get(i);
9640            BasePermission bp = mSettings.mPermissions.get(perm);
9641            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9642                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9643                if (appOpPkgs != null) {
9644                    appOpPkgs.remove(pkg.packageName);
9645                    if (appOpPkgs.isEmpty()) {
9646                        mAppOpPermissionPackages.remove(perm);
9647                    }
9648                }
9649            }
9650        }
9651        if (r != null) {
9652            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9653        }
9654
9655        N = pkg.instrumentation.size();
9656        r = null;
9657        for (i=0; i<N; i++) {
9658            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9659            mInstrumentation.remove(a.getComponentName());
9660            if (DEBUG_REMOVE && chatty) {
9661                if (r == null) {
9662                    r = new StringBuilder(256);
9663                } else {
9664                    r.append(' ');
9665                }
9666                r.append(a.info.name);
9667            }
9668        }
9669        if (r != null) {
9670            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9671        }
9672
9673        r = null;
9674        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9675            // Only system apps can hold shared libraries.
9676            if (pkg.libraryNames != null) {
9677                for (i=0; i<pkg.libraryNames.size(); i++) {
9678                    String name = pkg.libraryNames.get(i);
9679                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9680                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9681                        mSharedLibraries.remove(name);
9682                        if (DEBUG_REMOVE && chatty) {
9683                            if (r == null) {
9684                                r = new StringBuilder(256);
9685                            } else {
9686                                r.append(' ');
9687                            }
9688                            r.append(name);
9689                        }
9690                    }
9691                }
9692            }
9693        }
9694        if (r != null) {
9695            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9696        }
9697    }
9698
9699    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9700        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9701            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9702                return true;
9703            }
9704        }
9705        return false;
9706    }
9707
9708    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9709    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9710    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9711
9712    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9713        // Update the parent permissions
9714        updatePermissionsLPw(pkg.packageName, pkg, flags);
9715        // Update the child permissions
9716        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9717        for (int i = 0; i < childCount; i++) {
9718            PackageParser.Package childPkg = pkg.childPackages.get(i);
9719            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9720        }
9721    }
9722
9723    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9724            int flags) {
9725        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9726        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9727    }
9728
9729    private void updatePermissionsLPw(String changingPkg,
9730            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9731        // Make sure there are no dangling permission trees.
9732        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9733        while (it.hasNext()) {
9734            final BasePermission bp = it.next();
9735            if (bp.packageSetting == null) {
9736                // We may not yet have parsed the package, so just see if
9737                // we still know about its settings.
9738                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9739            }
9740            if (bp.packageSetting == null) {
9741                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9742                        + " from package " + bp.sourcePackage);
9743                it.remove();
9744            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9745                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9746                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9747                            + " from package " + bp.sourcePackage);
9748                    flags |= UPDATE_PERMISSIONS_ALL;
9749                    it.remove();
9750                }
9751            }
9752        }
9753
9754        // Make sure all dynamic permissions have been assigned to a package,
9755        // and make sure there are no dangling permissions.
9756        it = mSettings.mPermissions.values().iterator();
9757        while (it.hasNext()) {
9758            final BasePermission bp = it.next();
9759            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9760                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9761                        + bp.name + " pkg=" + bp.sourcePackage
9762                        + " info=" + bp.pendingInfo);
9763                if (bp.packageSetting == null && bp.pendingInfo != null) {
9764                    final BasePermission tree = findPermissionTreeLP(bp.name);
9765                    if (tree != null && tree.perm != null) {
9766                        bp.packageSetting = tree.packageSetting;
9767                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9768                                new PermissionInfo(bp.pendingInfo));
9769                        bp.perm.info.packageName = tree.perm.info.packageName;
9770                        bp.perm.info.name = bp.name;
9771                        bp.uid = tree.uid;
9772                    }
9773                }
9774            }
9775            if (bp.packageSetting == null) {
9776                // We may not yet have parsed the package, so just see if
9777                // we still know about its settings.
9778                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9779            }
9780            if (bp.packageSetting == null) {
9781                Slog.w(TAG, "Removing dangling permission: " + bp.name
9782                        + " from package " + bp.sourcePackage);
9783                it.remove();
9784            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9785                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9786                    Slog.i(TAG, "Removing old permission: " + bp.name
9787                            + " from package " + bp.sourcePackage);
9788                    flags |= UPDATE_PERMISSIONS_ALL;
9789                    it.remove();
9790                }
9791            }
9792        }
9793
9794        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9795        // Now update the permissions for all packages, in particular
9796        // replace the granted permissions of the system packages.
9797        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9798            for (PackageParser.Package pkg : mPackages.values()) {
9799                if (pkg != pkgInfo) {
9800                    // Only replace for packages on requested volume
9801                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9802                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9803                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9804                    grantPermissionsLPw(pkg, replace, changingPkg);
9805                }
9806            }
9807        }
9808
9809        if (pkgInfo != null) {
9810            // Only replace for packages on requested volume
9811            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9812            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9813                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9814            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9815        }
9816        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9817    }
9818
9819    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9820            String packageOfInterest) {
9821        // IMPORTANT: There are two types of permissions: install and runtime.
9822        // Install time permissions are granted when the app is installed to
9823        // all device users and users added in the future. Runtime permissions
9824        // are granted at runtime explicitly to specific users. Normal and signature
9825        // protected permissions are install time permissions. Dangerous permissions
9826        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9827        // otherwise they are runtime permissions. This function does not manage
9828        // runtime permissions except for the case an app targeting Lollipop MR1
9829        // being upgraded to target a newer SDK, in which case dangerous permissions
9830        // are transformed from install time to runtime ones.
9831
9832        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9833        if (ps == null) {
9834            return;
9835        }
9836
9837        PermissionsState permissionsState = ps.getPermissionsState();
9838        PermissionsState origPermissions = permissionsState;
9839
9840        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9841
9842        boolean runtimePermissionsRevoked = false;
9843        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9844
9845        boolean changedInstallPermission = false;
9846
9847        if (replace) {
9848            ps.installPermissionsFixed = false;
9849            if (!ps.isSharedUser()) {
9850                origPermissions = new PermissionsState(permissionsState);
9851                permissionsState.reset();
9852            } else {
9853                // We need to know only about runtime permission changes since the
9854                // calling code always writes the install permissions state but
9855                // the runtime ones are written only if changed. The only cases of
9856                // changed runtime permissions here are promotion of an install to
9857                // runtime and revocation of a runtime from a shared user.
9858                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9859                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9860                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9861                    runtimePermissionsRevoked = true;
9862                }
9863            }
9864        }
9865
9866        permissionsState.setGlobalGids(mGlobalGids);
9867
9868        final int N = pkg.requestedPermissions.size();
9869        for (int i=0; i<N; i++) {
9870            final String name = pkg.requestedPermissions.get(i);
9871            final BasePermission bp = mSettings.mPermissions.get(name);
9872
9873            if (DEBUG_INSTALL) {
9874                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9875            }
9876
9877            if (bp == null || bp.packageSetting == null) {
9878                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9879                    Slog.w(TAG, "Unknown permission " + name
9880                            + " in package " + pkg.packageName);
9881                }
9882                continue;
9883            }
9884
9885            final String perm = bp.name;
9886            boolean allowedSig = false;
9887            int grant = GRANT_DENIED;
9888
9889            // Keep track of app op permissions.
9890            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9891                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9892                if (pkgs == null) {
9893                    pkgs = new ArraySet<>();
9894                    mAppOpPermissionPackages.put(bp.name, pkgs);
9895                }
9896                pkgs.add(pkg.packageName);
9897            }
9898
9899            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9900            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9901                    >= Build.VERSION_CODES.M;
9902            switch (level) {
9903                case PermissionInfo.PROTECTION_NORMAL: {
9904                    // For all apps normal permissions are install time ones.
9905                    grant = GRANT_INSTALL;
9906                } break;
9907
9908                case PermissionInfo.PROTECTION_DANGEROUS: {
9909                    // If a permission review is required for legacy apps we represent
9910                    // their permissions as always granted runtime ones since we need
9911                    // to keep the review required permission flag per user while an
9912                    // install permission's state is shared across all users.
9913                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9914                        // For legacy apps dangerous permissions are install time ones.
9915                        grant = GRANT_INSTALL;
9916                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9917                        // For legacy apps that became modern, install becomes runtime.
9918                        grant = GRANT_UPGRADE;
9919                    } else if (mPromoteSystemApps
9920                            && isSystemApp(ps)
9921                            && mExistingSystemPackages.contains(ps.name)) {
9922                        // For legacy system apps, install becomes runtime.
9923                        // We cannot check hasInstallPermission() for system apps since those
9924                        // permissions were granted implicitly and not persisted pre-M.
9925                        grant = GRANT_UPGRADE;
9926                    } else {
9927                        // For modern apps keep runtime permissions unchanged.
9928                        grant = GRANT_RUNTIME;
9929                    }
9930                } break;
9931
9932                case PermissionInfo.PROTECTION_SIGNATURE: {
9933                    // For all apps signature permissions are install time ones.
9934                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9935                    if (allowedSig) {
9936                        grant = GRANT_INSTALL;
9937                    }
9938                } break;
9939            }
9940
9941            if (DEBUG_INSTALL) {
9942                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9943            }
9944
9945            if (grant != GRANT_DENIED) {
9946                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9947                    // If this is an existing, non-system package, then
9948                    // we can't add any new permissions to it.
9949                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9950                        // Except...  if this is a permission that was added
9951                        // to the platform (note: need to only do this when
9952                        // updating the platform).
9953                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9954                            grant = GRANT_DENIED;
9955                        }
9956                    }
9957                }
9958
9959                switch (grant) {
9960                    case GRANT_INSTALL: {
9961                        // Revoke this as runtime permission to handle the case of
9962                        // a runtime permission being downgraded to an install one.
9963                        // Also in permission review mode we keep dangerous permissions
9964                        // for legacy apps
9965                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9966                            if (origPermissions.getRuntimePermissionState(
9967                                    bp.name, userId) != null) {
9968                                // Revoke the runtime permission and clear the flags.
9969                                origPermissions.revokeRuntimePermission(bp, userId);
9970                                origPermissions.updatePermissionFlags(bp, userId,
9971                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9972                                // If we revoked a permission permission, we have to write.
9973                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9974                                        changedRuntimePermissionUserIds, userId);
9975                            }
9976                        }
9977                        // Grant an install permission.
9978                        if (permissionsState.grantInstallPermission(bp) !=
9979                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9980                            changedInstallPermission = true;
9981                        }
9982                    } break;
9983
9984                    case GRANT_RUNTIME: {
9985                        // Grant previously granted runtime permissions.
9986                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9987                            PermissionState permissionState = origPermissions
9988                                    .getRuntimePermissionState(bp.name, userId);
9989                            int flags = permissionState != null
9990                                    ? permissionState.getFlags() : 0;
9991                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9992                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9993                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9994                                    // If we cannot put the permission as it was, we have to write.
9995                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9996                                            changedRuntimePermissionUserIds, userId);
9997                                }
9998                                // If the app supports runtime permissions no need for a review.
9999                                if (Build.PERMISSIONS_REVIEW_REQUIRED
10000                                        && appSupportsRuntimePermissions
10001                                        && (flags & PackageManager
10002                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10003                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10004                                    // Since we changed the flags, we have to write.
10005                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10006                                            changedRuntimePermissionUserIds, userId);
10007                                }
10008                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
10009                                    && !appSupportsRuntimePermissions) {
10010                                // For legacy apps that need a permission review, every new
10011                                // runtime permission is granted but it is pending a review.
10012                                // We also need to review only platform defined runtime
10013                                // permissions as these are the only ones the platform knows
10014                                // how to disable the API to simulate revocation as legacy
10015                                // apps don't expect to run with revoked permissions.
10016                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10017                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10018                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10019                                        // We changed the flags, hence have to write.
10020                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10021                                                changedRuntimePermissionUserIds, userId);
10022                                    }
10023                                }
10024                                if (permissionsState.grantRuntimePermission(bp, userId)
10025                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10026                                    // We changed the permission, hence have to write.
10027                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10028                                            changedRuntimePermissionUserIds, userId);
10029                                }
10030                            }
10031                            // Propagate the permission flags.
10032                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10033                        }
10034                    } break;
10035
10036                    case GRANT_UPGRADE: {
10037                        // Grant runtime permissions for a previously held install permission.
10038                        PermissionState permissionState = origPermissions
10039                                .getInstallPermissionState(bp.name);
10040                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10041
10042                        if (origPermissions.revokeInstallPermission(bp)
10043                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10044                            // We will be transferring the permission flags, so clear them.
10045                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10046                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10047                            changedInstallPermission = true;
10048                        }
10049
10050                        // If the permission is not to be promoted to runtime we ignore it and
10051                        // also its other flags as they are not applicable to install permissions.
10052                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10053                            for (int userId : currentUserIds) {
10054                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10055                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10056                                    // Transfer the permission flags.
10057                                    permissionsState.updatePermissionFlags(bp, userId,
10058                                            flags, flags);
10059                                    // If we granted the permission, we have to write.
10060                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10061                                            changedRuntimePermissionUserIds, userId);
10062                                }
10063                            }
10064                        }
10065                    } break;
10066
10067                    default: {
10068                        if (packageOfInterest == null
10069                                || packageOfInterest.equals(pkg.packageName)) {
10070                            Slog.w(TAG, "Not granting permission " + perm
10071                                    + " to package " + pkg.packageName
10072                                    + " because it was previously installed without");
10073                        }
10074                    } break;
10075                }
10076            } else {
10077                if (permissionsState.revokeInstallPermission(bp) !=
10078                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10079                    // Also drop the permission flags.
10080                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10081                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10082                    changedInstallPermission = true;
10083                    Slog.i(TAG, "Un-granting permission " + perm
10084                            + " from package " + pkg.packageName
10085                            + " (protectionLevel=" + bp.protectionLevel
10086                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10087                            + ")");
10088                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10089                    // Don't print warning for app op permissions, since it is fine for them
10090                    // not to be granted, there is a UI for the user to decide.
10091                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10092                        Slog.w(TAG, "Not granting permission " + perm
10093                                + " to package " + pkg.packageName
10094                                + " (protectionLevel=" + bp.protectionLevel
10095                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10096                                + ")");
10097                    }
10098                }
10099            }
10100        }
10101
10102        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10103                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10104            // This is the first that we have heard about this package, so the
10105            // permissions we have now selected are fixed until explicitly
10106            // changed.
10107            ps.installPermissionsFixed = true;
10108        }
10109
10110        // Persist the runtime permissions state for users with changes. If permissions
10111        // were revoked because no app in the shared user declares them we have to
10112        // write synchronously to avoid losing runtime permissions state.
10113        for (int userId : changedRuntimePermissionUserIds) {
10114            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10115        }
10116    }
10117
10118    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10119        boolean allowed = false;
10120        final int NP = PackageParser.NEW_PERMISSIONS.length;
10121        for (int ip=0; ip<NP; ip++) {
10122            final PackageParser.NewPermissionInfo npi
10123                    = PackageParser.NEW_PERMISSIONS[ip];
10124            if (npi.name.equals(perm)
10125                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10126                allowed = true;
10127                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10128                        + pkg.packageName);
10129                break;
10130            }
10131        }
10132        return allowed;
10133    }
10134
10135    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10136            BasePermission bp, PermissionsState origPermissions) {
10137        boolean allowed;
10138        allowed = (compareSignatures(
10139                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10140                        == PackageManager.SIGNATURE_MATCH)
10141                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10142                        == PackageManager.SIGNATURE_MATCH);
10143        if (!allowed && (bp.protectionLevel
10144                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10145            if (isSystemApp(pkg)) {
10146                // For updated system applications, a system permission
10147                // is granted only if it had been defined by the original application.
10148                if (pkg.isUpdatedSystemApp()) {
10149                    final PackageSetting sysPs = mSettings
10150                            .getDisabledSystemPkgLPr(pkg.packageName);
10151                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10152                        // If the original was granted this permission, we take
10153                        // that grant decision as read and propagate it to the
10154                        // update.
10155                        if (sysPs.isPrivileged()) {
10156                            allowed = true;
10157                        }
10158                    } else {
10159                        // The system apk may have been updated with an older
10160                        // version of the one on the data partition, but which
10161                        // granted a new system permission that it didn't have
10162                        // before.  In this case we do want to allow the app to
10163                        // now get the new permission if the ancestral apk is
10164                        // privileged to get it.
10165                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10166                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10167                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10168                                    allowed = true;
10169                                    break;
10170                                }
10171                            }
10172                        }
10173                        // Also if a privileged parent package on the system image or any of
10174                        // its children requested a privileged permission, the updated child
10175                        // packages can also get the permission.
10176                        if (pkg.parentPackage != null) {
10177                            final PackageSetting disabledSysParentPs = mSettings
10178                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10179                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10180                                    && disabledSysParentPs.isPrivileged()) {
10181                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10182                                    allowed = true;
10183                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10184                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10185                                    for (int i = 0; i < count; i++) {
10186                                        PackageParser.Package disabledSysChildPkg =
10187                                                disabledSysParentPs.pkg.childPackages.get(i);
10188                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10189                                                perm)) {
10190                                            allowed = true;
10191                                            break;
10192                                        }
10193                                    }
10194                                }
10195                            }
10196                        }
10197                    }
10198                } else {
10199                    allowed = isPrivilegedApp(pkg);
10200                }
10201            }
10202        }
10203        if (!allowed) {
10204            if (!allowed && (bp.protectionLevel
10205                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10206                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10207                // If this was a previously normal/dangerous permission that got moved
10208                // to a system permission as part of the runtime permission redesign, then
10209                // we still want to blindly grant it to old apps.
10210                allowed = true;
10211            }
10212            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10213                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10214                // If this permission is to be granted to the system installer and
10215                // this app is an installer, then it gets the permission.
10216                allowed = true;
10217            }
10218            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10219                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10220                // If this permission is to be granted to the system verifier and
10221                // this app is a verifier, then it gets the permission.
10222                allowed = true;
10223            }
10224            if (!allowed && (bp.protectionLevel
10225                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10226                    && isSystemApp(pkg)) {
10227                // Any pre-installed system app is allowed to get this permission.
10228                allowed = true;
10229            }
10230            if (!allowed && (bp.protectionLevel
10231                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10232                // For development permissions, a development permission
10233                // is granted only if it was already granted.
10234                allowed = origPermissions.hasInstallPermission(perm);
10235            }
10236            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10237                    && pkg.packageName.equals(mSetupWizardPackage)) {
10238                // If this permission is to be granted to the system setup wizard and
10239                // this app is a setup wizard, then it gets the permission.
10240                allowed = true;
10241            }
10242        }
10243        return allowed;
10244    }
10245
10246    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10247        final int permCount = pkg.requestedPermissions.size();
10248        for (int j = 0; j < permCount; j++) {
10249            String requestedPermission = pkg.requestedPermissions.get(j);
10250            if (permission.equals(requestedPermission)) {
10251                return true;
10252            }
10253        }
10254        return false;
10255    }
10256
10257    final class ActivityIntentResolver
10258            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10259        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10260                boolean defaultOnly, int userId) {
10261            if (!sUserManager.exists(userId)) return null;
10262            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10263            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10264        }
10265
10266        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10267                int userId) {
10268            if (!sUserManager.exists(userId)) return null;
10269            mFlags = flags;
10270            return super.queryIntent(intent, resolvedType,
10271                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10272        }
10273
10274        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10275                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10276            if (!sUserManager.exists(userId)) return null;
10277            if (packageActivities == null) {
10278                return null;
10279            }
10280            mFlags = flags;
10281            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10282            final int N = packageActivities.size();
10283            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10284                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10285
10286            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10287            for (int i = 0; i < N; ++i) {
10288                intentFilters = packageActivities.get(i).intents;
10289                if (intentFilters != null && intentFilters.size() > 0) {
10290                    PackageParser.ActivityIntentInfo[] array =
10291                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10292                    intentFilters.toArray(array);
10293                    listCut.add(array);
10294                }
10295            }
10296            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10297        }
10298
10299        /**
10300         * Finds a privileged activity that matches the specified activity names.
10301         */
10302        private PackageParser.Activity findMatchingActivity(
10303                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10304            for (PackageParser.Activity sysActivity : activityList) {
10305                if (sysActivity.info.name.equals(activityInfo.name)) {
10306                    return sysActivity;
10307                }
10308                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10309                    return sysActivity;
10310                }
10311                if (sysActivity.info.targetActivity != null) {
10312                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10313                        return sysActivity;
10314                    }
10315                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10316                        return sysActivity;
10317                    }
10318                }
10319            }
10320            return null;
10321        }
10322
10323        public class IterGenerator<E> {
10324            public Iterator<E> generate(ActivityIntentInfo info) {
10325                return null;
10326            }
10327        }
10328
10329        public class ActionIterGenerator extends IterGenerator<String> {
10330            @Override
10331            public Iterator<String> generate(ActivityIntentInfo info) {
10332                return info.actionsIterator();
10333            }
10334        }
10335
10336        public class CategoriesIterGenerator extends IterGenerator<String> {
10337            @Override
10338            public Iterator<String> generate(ActivityIntentInfo info) {
10339                return info.categoriesIterator();
10340            }
10341        }
10342
10343        public class SchemesIterGenerator extends IterGenerator<String> {
10344            @Override
10345            public Iterator<String> generate(ActivityIntentInfo info) {
10346                return info.schemesIterator();
10347            }
10348        }
10349
10350        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10351            @Override
10352            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10353                return info.authoritiesIterator();
10354            }
10355        }
10356
10357        /**
10358         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10359         * MODIFIED. Do not pass in a list that should not be changed.
10360         */
10361        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10362                IterGenerator<T> generator, Iterator<T> searchIterator) {
10363            // loop through the set of actions; every one must be found in the intent filter
10364            while (searchIterator.hasNext()) {
10365                // we must have at least one filter in the list to consider a match
10366                if (intentList.size() == 0) {
10367                    break;
10368                }
10369
10370                final T searchAction = searchIterator.next();
10371
10372                // loop through the set of intent filters
10373                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10374                while (intentIter.hasNext()) {
10375                    final ActivityIntentInfo intentInfo = intentIter.next();
10376                    boolean selectionFound = false;
10377
10378                    // loop through the intent filter's selection criteria; at least one
10379                    // of them must match the searched criteria
10380                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10381                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10382                        final T intentSelection = intentSelectionIter.next();
10383                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10384                            selectionFound = true;
10385                            break;
10386                        }
10387                    }
10388
10389                    // the selection criteria wasn't found in this filter's set; this filter
10390                    // is not a potential match
10391                    if (!selectionFound) {
10392                        intentIter.remove();
10393                    }
10394                }
10395            }
10396        }
10397
10398        private boolean isProtectedAction(ActivityIntentInfo filter) {
10399            final Iterator<String> actionsIter = filter.actionsIterator();
10400            while (actionsIter != null && actionsIter.hasNext()) {
10401                final String filterAction = actionsIter.next();
10402                if (PROTECTED_ACTIONS.contains(filterAction)) {
10403                    return true;
10404                }
10405            }
10406            return false;
10407        }
10408
10409        /**
10410         * Adjusts the priority of the given intent filter according to policy.
10411         * <p>
10412         * <ul>
10413         * <li>The priority for non privileged applications is capped to '0'</li>
10414         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10415         * <li>The priority for unbundled updates to privileged applications is capped to the
10416         *      priority defined on the system partition</li>
10417         * </ul>
10418         * <p>
10419         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10420         * allowed to obtain any priority on any action.
10421         */
10422        private void adjustPriority(
10423                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10424            // nothing to do; priority is fine as-is
10425            if (intent.getPriority() <= 0) {
10426                return;
10427            }
10428
10429            final ActivityInfo activityInfo = intent.activity.info;
10430            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10431
10432            final boolean privilegedApp =
10433                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10434            if (!privilegedApp) {
10435                // non-privileged applications can never define a priority >0
10436                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10437                        + " package: " + applicationInfo.packageName
10438                        + " activity: " + intent.activity.className
10439                        + " origPrio: " + intent.getPriority());
10440                intent.setPriority(0);
10441                return;
10442            }
10443
10444            if (systemActivities == null) {
10445                // the system package is not disabled; we're parsing the system partition
10446                if (isProtectedAction(intent)) {
10447                    if (mDeferProtectedFilters) {
10448                        // We can't deal with these just yet. No component should ever obtain a
10449                        // >0 priority for a protected actions, with ONE exception -- the setup
10450                        // wizard. The setup wizard, however, cannot be known until we're able to
10451                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10452                        // until all intent filters have been processed. Chicken, meet egg.
10453                        // Let the filter temporarily have a high priority and rectify the
10454                        // priorities after all system packages have been scanned.
10455                        mProtectedFilters.add(intent);
10456                        if (DEBUG_FILTERS) {
10457                            Slog.i(TAG, "Protected action; save for later;"
10458                                    + " package: " + applicationInfo.packageName
10459                                    + " activity: " + intent.activity.className
10460                                    + " origPrio: " + intent.getPriority());
10461                        }
10462                        return;
10463                    } else {
10464                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10465                            Slog.i(TAG, "No setup wizard;"
10466                                + " All protected intents capped to priority 0");
10467                        }
10468                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10469                            if (DEBUG_FILTERS) {
10470                                Slog.i(TAG, "Found setup wizard;"
10471                                    + " allow priority " + intent.getPriority() + ";"
10472                                    + " package: " + intent.activity.info.packageName
10473                                    + " activity: " + intent.activity.className
10474                                    + " priority: " + intent.getPriority());
10475                            }
10476                            // setup wizard gets whatever it wants
10477                            return;
10478                        }
10479                        Slog.w(TAG, "Protected action; cap priority to 0;"
10480                                + " package: " + intent.activity.info.packageName
10481                                + " activity: " + intent.activity.className
10482                                + " origPrio: " + intent.getPriority());
10483                        intent.setPriority(0);
10484                        return;
10485                    }
10486                }
10487                // privileged apps on the system image get whatever priority they request
10488                return;
10489            }
10490
10491            // privileged app unbundled update ... try to find the same activity
10492            final PackageParser.Activity foundActivity =
10493                    findMatchingActivity(systemActivities, activityInfo);
10494            if (foundActivity == null) {
10495                // this is a new activity; it cannot obtain >0 priority
10496                if (DEBUG_FILTERS) {
10497                    Slog.i(TAG, "New activity; cap priority to 0;"
10498                            + " package: " + applicationInfo.packageName
10499                            + " activity: " + intent.activity.className
10500                            + " origPrio: " + intent.getPriority());
10501                }
10502                intent.setPriority(0);
10503                return;
10504            }
10505
10506            // found activity, now check for filter equivalence
10507
10508            // a shallow copy is enough; we modify the list, not its contents
10509            final List<ActivityIntentInfo> intentListCopy =
10510                    new ArrayList<>(foundActivity.intents);
10511            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10512
10513            // find matching action subsets
10514            final Iterator<String> actionsIterator = intent.actionsIterator();
10515            if (actionsIterator != null) {
10516                getIntentListSubset(
10517                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10518                if (intentListCopy.size() == 0) {
10519                    // no more intents to match; we're not equivalent
10520                    if (DEBUG_FILTERS) {
10521                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10522                                + " package: " + applicationInfo.packageName
10523                                + " activity: " + intent.activity.className
10524                                + " origPrio: " + intent.getPriority());
10525                    }
10526                    intent.setPriority(0);
10527                    return;
10528                }
10529            }
10530
10531            // find matching category subsets
10532            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10533            if (categoriesIterator != null) {
10534                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10535                        categoriesIterator);
10536                if (intentListCopy.size() == 0) {
10537                    // no more intents to match; we're not equivalent
10538                    if (DEBUG_FILTERS) {
10539                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10540                                + " package: " + applicationInfo.packageName
10541                                + " activity: " + intent.activity.className
10542                                + " origPrio: " + intent.getPriority());
10543                    }
10544                    intent.setPriority(0);
10545                    return;
10546                }
10547            }
10548
10549            // find matching schemes subsets
10550            final Iterator<String> schemesIterator = intent.schemesIterator();
10551            if (schemesIterator != null) {
10552                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10553                        schemesIterator);
10554                if (intentListCopy.size() == 0) {
10555                    // no more intents to match; we're not equivalent
10556                    if (DEBUG_FILTERS) {
10557                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10558                                + " package: " + applicationInfo.packageName
10559                                + " activity: " + intent.activity.className
10560                                + " origPrio: " + intent.getPriority());
10561                    }
10562                    intent.setPriority(0);
10563                    return;
10564                }
10565            }
10566
10567            // find matching authorities subsets
10568            final Iterator<IntentFilter.AuthorityEntry>
10569                    authoritiesIterator = intent.authoritiesIterator();
10570            if (authoritiesIterator != null) {
10571                getIntentListSubset(intentListCopy,
10572                        new AuthoritiesIterGenerator(),
10573                        authoritiesIterator);
10574                if (intentListCopy.size() == 0) {
10575                    // no more intents to match; we're not equivalent
10576                    if (DEBUG_FILTERS) {
10577                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10578                                + " package: " + applicationInfo.packageName
10579                                + " activity: " + intent.activity.className
10580                                + " origPrio: " + intent.getPriority());
10581                    }
10582                    intent.setPriority(0);
10583                    return;
10584                }
10585            }
10586
10587            // we found matching filter(s); app gets the max priority of all intents
10588            int cappedPriority = 0;
10589            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10590                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10591            }
10592            if (intent.getPriority() > cappedPriority) {
10593                if (DEBUG_FILTERS) {
10594                    Slog.i(TAG, "Found matching filter(s);"
10595                            + " cap priority to " + cappedPriority + ";"
10596                            + " package: " + applicationInfo.packageName
10597                            + " activity: " + intent.activity.className
10598                            + " origPrio: " + intent.getPriority());
10599                }
10600                intent.setPriority(cappedPriority);
10601                return;
10602            }
10603            // all this for nothing; the requested priority was <= what was on the system
10604        }
10605
10606        public final void addActivity(PackageParser.Activity a, String type) {
10607            mActivities.put(a.getComponentName(), a);
10608            if (DEBUG_SHOW_INFO)
10609                Log.v(
10610                TAG, "  " + type + " " +
10611                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10612            if (DEBUG_SHOW_INFO)
10613                Log.v(TAG, "    Class=" + a.info.name);
10614            final int NI = a.intents.size();
10615            for (int j=0; j<NI; j++) {
10616                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10617                if ("activity".equals(type)) {
10618                    final PackageSetting ps =
10619                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10620                    final List<PackageParser.Activity> systemActivities =
10621                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10622                    adjustPriority(systemActivities, intent);
10623                }
10624                if (DEBUG_SHOW_INFO) {
10625                    Log.v(TAG, "    IntentFilter:");
10626                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10627                }
10628                if (!intent.debugCheck()) {
10629                    Log.w(TAG, "==> For Activity " + a.info.name);
10630                }
10631                addFilter(intent);
10632            }
10633        }
10634
10635        public final void removeActivity(PackageParser.Activity a, String type) {
10636            mActivities.remove(a.getComponentName());
10637            if (DEBUG_SHOW_INFO) {
10638                Log.v(TAG, "  " + type + " "
10639                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10640                                : a.info.name) + ":");
10641                Log.v(TAG, "    Class=" + a.info.name);
10642            }
10643            final int NI = a.intents.size();
10644            for (int j=0; j<NI; j++) {
10645                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10646                if (DEBUG_SHOW_INFO) {
10647                    Log.v(TAG, "    IntentFilter:");
10648                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10649                }
10650                removeFilter(intent);
10651            }
10652        }
10653
10654        @Override
10655        protected boolean allowFilterResult(
10656                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10657            ActivityInfo filterAi = filter.activity.info;
10658            for (int i=dest.size()-1; i>=0; i--) {
10659                ActivityInfo destAi = dest.get(i).activityInfo;
10660                if (destAi.name == filterAi.name
10661                        && destAi.packageName == filterAi.packageName) {
10662                    return false;
10663                }
10664            }
10665            return true;
10666        }
10667
10668        @Override
10669        protected ActivityIntentInfo[] newArray(int size) {
10670            return new ActivityIntentInfo[size];
10671        }
10672
10673        @Override
10674        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10675            if (!sUserManager.exists(userId)) return true;
10676            PackageParser.Package p = filter.activity.owner;
10677            if (p != null) {
10678                PackageSetting ps = (PackageSetting)p.mExtras;
10679                if (ps != null) {
10680                    // System apps are never considered stopped for purposes of
10681                    // filtering, because there may be no way for the user to
10682                    // actually re-launch them.
10683                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10684                            && ps.getStopped(userId);
10685                }
10686            }
10687            return false;
10688        }
10689
10690        @Override
10691        protected boolean isPackageForFilter(String packageName,
10692                PackageParser.ActivityIntentInfo info) {
10693            return packageName.equals(info.activity.owner.packageName);
10694        }
10695
10696        @Override
10697        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10698                int match, int userId) {
10699            if (!sUserManager.exists(userId)) return null;
10700            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10701                return null;
10702            }
10703            final PackageParser.Activity activity = info.activity;
10704            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10705            if (ps == null) {
10706                return null;
10707            }
10708            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10709                    ps.readUserState(userId), userId);
10710            if (ai == null) {
10711                return null;
10712            }
10713            final ResolveInfo res = new ResolveInfo();
10714            res.activityInfo = ai;
10715            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10716                res.filter = info;
10717            }
10718            if (info != null) {
10719                res.handleAllWebDataURI = info.handleAllWebDataURI();
10720            }
10721            res.priority = info.getPriority();
10722            res.preferredOrder = activity.owner.mPreferredOrder;
10723            //System.out.println("Result: " + res.activityInfo.className +
10724            //                   " = " + res.priority);
10725            res.match = match;
10726            res.isDefault = info.hasDefault;
10727            res.labelRes = info.labelRes;
10728            res.nonLocalizedLabel = info.nonLocalizedLabel;
10729            if (userNeedsBadging(userId)) {
10730                res.noResourceId = true;
10731            } else {
10732                res.icon = info.icon;
10733            }
10734            res.iconResourceId = info.icon;
10735            res.system = res.activityInfo.applicationInfo.isSystemApp();
10736            return res;
10737        }
10738
10739        @Override
10740        protected void sortResults(List<ResolveInfo> results) {
10741            Collections.sort(results, mResolvePrioritySorter);
10742        }
10743
10744        @Override
10745        protected void dumpFilter(PrintWriter out, String prefix,
10746                PackageParser.ActivityIntentInfo filter) {
10747            out.print(prefix); out.print(
10748                    Integer.toHexString(System.identityHashCode(filter.activity)));
10749                    out.print(' ');
10750                    filter.activity.printComponentShortName(out);
10751                    out.print(" filter ");
10752                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10753        }
10754
10755        @Override
10756        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10757            return filter.activity;
10758        }
10759
10760        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10761            PackageParser.Activity activity = (PackageParser.Activity)label;
10762            out.print(prefix); out.print(
10763                    Integer.toHexString(System.identityHashCode(activity)));
10764                    out.print(' ');
10765                    activity.printComponentShortName(out);
10766            if (count > 1) {
10767                out.print(" ("); out.print(count); out.print(" filters)");
10768            }
10769            out.println();
10770        }
10771
10772        // Keys are String (activity class name), values are Activity.
10773        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10774                = new ArrayMap<ComponentName, PackageParser.Activity>();
10775        private int mFlags;
10776    }
10777
10778    private final class ServiceIntentResolver
10779            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10780        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10781                boolean defaultOnly, int userId) {
10782            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10783            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10784        }
10785
10786        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10787                int userId) {
10788            if (!sUserManager.exists(userId)) return null;
10789            mFlags = flags;
10790            return super.queryIntent(intent, resolvedType,
10791                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10792        }
10793
10794        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10795                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10796            if (!sUserManager.exists(userId)) return null;
10797            if (packageServices == null) {
10798                return null;
10799            }
10800            mFlags = flags;
10801            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10802            final int N = packageServices.size();
10803            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10804                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10805
10806            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10807            for (int i = 0; i < N; ++i) {
10808                intentFilters = packageServices.get(i).intents;
10809                if (intentFilters != null && intentFilters.size() > 0) {
10810                    PackageParser.ServiceIntentInfo[] array =
10811                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10812                    intentFilters.toArray(array);
10813                    listCut.add(array);
10814                }
10815            }
10816            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10817        }
10818
10819        public final void addService(PackageParser.Service s) {
10820            mServices.put(s.getComponentName(), s);
10821            if (DEBUG_SHOW_INFO) {
10822                Log.v(TAG, "  "
10823                        + (s.info.nonLocalizedLabel != null
10824                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10825                Log.v(TAG, "    Class=" + s.info.name);
10826            }
10827            final int NI = s.intents.size();
10828            int j;
10829            for (j=0; j<NI; j++) {
10830                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10831                if (DEBUG_SHOW_INFO) {
10832                    Log.v(TAG, "    IntentFilter:");
10833                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10834                }
10835                if (!intent.debugCheck()) {
10836                    Log.w(TAG, "==> For Service " + s.info.name);
10837                }
10838                addFilter(intent);
10839            }
10840        }
10841
10842        public final void removeService(PackageParser.Service s) {
10843            mServices.remove(s.getComponentName());
10844            if (DEBUG_SHOW_INFO) {
10845                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10846                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10847                Log.v(TAG, "    Class=" + s.info.name);
10848            }
10849            final int NI = s.intents.size();
10850            int j;
10851            for (j=0; j<NI; j++) {
10852                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10853                if (DEBUG_SHOW_INFO) {
10854                    Log.v(TAG, "    IntentFilter:");
10855                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10856                }
10857                removeFilter(intent);
10858            }
10859        }
10860
10861        @Override
10862        protected boolean allowFilterResult(
10863                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10864            ServiceInfo filterSi = filter.service.info;
10865            for (int i=dest.size()-1; i>=0; i--) {
10866                ServiceInfo destAi = dest.get(i).serviceInfo;
10867                if (destAi.name == filterSi.name
10868                        && destAi.packageName == filterSi.packageName) {
10869                    return false;
10870                }
10871            }
10872            return true;
10873        }
10874
10875        @Override
10876        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10877            return new PackageParser.ServiceIntentInfo[size];
10878        }
10879
10880        @Override
10881        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10882            if (!sUserManager.exists(userId)) return true;
10883            PackageParser.Package p = filter.service.owner;
10884            if (p != null) {
10885                PackageSetting ps = (PackageSetting)p.mExtras;
10886                if (ps != null) {
10887                    // System apps are never considered stopped for purposes of
10888                    // filtering, because there may be no way for the user to
10889                    // actually re-launch them.
10890                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10891                            && ps.getStopped(userId);
10892                }
10893            }
10894            return false;
10895        }
10896
10897        @Override
10898        protected boolean isPackageForFilter(String packageName,
10899                PackageParser.ServiceIntentInfo info) {
10900            return packageName.equals(info.service.owner.packageName);
10901        }
10902
10903        @Override
10904        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10905                int match, int userId) {
10906            if (!sUserManager.exists(userId)) return null;
10907            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10908            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10909                return null;
10910            }
10911            final PackageParser.Service service = info.service;
10912            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10913            if (ps == null) {
10914                return null;
10915            }
10916            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10917                    ps.readUserState(userId), userId);
10918            if (si == null) {
10919                return null;
10920            }
10921            final ResolveInfo res = new ResolveInfo();
10922            res.serviceInfo = si;
10923            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10924                res.filter = filter;
10925            }
10926            res.priority = info.getPriority();
10927            res.preferredOrder = service.owner.mPreferredOrder;
10928            res.match = match;
10929            res.isDefault = info.hasDefault;
10930            res.labelRes = info.labelRes;
10931            res.nonLocalizedLabel = info.nonLocalizedLabel;
10932            res.icon = info.icon;
10933            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10934            return res;
10935        }
10936
10937        @Override
10938        protected void sortResults(List<ResolveInfo> results) {
10939            Collections.sort(results, mResolvePrioritySorter);
10940        }
10941
10942        @Override
10943        protected void dumpFilter(PrintWriter out, String prefix,
10944                PackageParser.ServiceIntentInfo filter) {
10945            out.print(prefix); out.print(
10946                    Integer.toHexString(System.identityHashCode(filter.service)));
10947                    out.print(' ');
10948                    filter.service.printComponentShortName(out);
10949                    out.print(" filter ");
10950                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10951        }
10952
10953        @Override
10954        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10955            return filter.service;
10956        }
10957
10958        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10959            PackageParser.Service service = (PackageParser.Service)label;
10960            out.print(prefix); out.print(
10961                    Integer.toHexString(System.identityHashCode(service)));
10962                    out.print(' ');
10963                    service.printComponentShortName(out);
10964            if (count > 1) {
10965                out.print(" ("); out.print(count); out.print(" filters)");
10966            }
10967            out.println();
10968        }
10969
10970//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10971//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10972//            final List<ResolveInfo> retList = Lists.newArrayList();
10973//            while (i.hasNext()) {
10974//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10975//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10976//                    retList.add(resolveInfo);
10977//                }
10978//            }
10979//            return retList;
10980//        }
10981
10982        // Keys are String (activity class name), values are Activity.
10983        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10984                = new ArrayMap<ComponentName, PackageParser.Service>();
10985        private int mFlags;
10986    };
10987
10988    private final class ProviderIntentResolver
10989            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10990        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10991                boolean defaultOnly, int userId) {
10992            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10993            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10994        }
10995
10996        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10997                int userId) {
10998            if (!sUserManager.exists(userId))
10999                return null;
11000            mFlags = flags;
11001            return super.queryIntent(intent, resolvedType,
11002                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11003        }
11004
11005        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11006                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11007            if (!sUserManager.exists(userId))
11008                return null;
11009            if (packageProviders == null) {
11010                return null;
11011            }
11012            mFlags = flags;
11013            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11014            final int N = packageProviders.size();
11015            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11016                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11017
11018            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11019            for (int i = 0; i < N; ++i) {
11020                intentFilters = packageProviders.get(i).intents;
11021                if (intentFilters != null && intentFilters.size() > 0) {
11022                    PackageParser.ProviderIntentInfo[] array =
11023                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11024                    intentFilters.toArray(array);
11025                    listCut.add(array);
11026                }
11027            }
11028            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11029        }
11030
11031        public final void addProvider(PackageParser.Provider p) {
11032            if (mProviders.containsKey(p.getComponentName())) {
11033                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11034                return;
11035            }
11036
11037            mProviders.put(p.getComponentName(), p);
11038            if (DEBUG_SHOW_INFO) {
11039                Log.v(TAG, "  "
11040                        + (p.info.nonLocalizedLabel != null
11041                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11042                Log.v(TAG, "    Class=" + p.info.name);
11043            }
11044            final int NI = p.intents.size();
11045            int j;
11046            for (j = 0; j < NI; j++) {
11047                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11048                if (DEBUG_SHOW_INFO) {
11049                    Log.v(TAG, "    IntentFilter:");
11050                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11051                }
11052                if (!intent.debugCheck()) {
11053                    Log.w(TAG, "==> For Provider " + p.info.name);
11054                }
11055                addFilter(intent);
11056            }
11057        }
11058
11059        public final void removeProvider(PackageParser.Provider p) {
11060            mProviders.remove(p.getComponentName());
11061            if (DEBUG_SHOW_INFO) {
11062                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11063                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11064                Log.v(TAG, "    Class=" + p.info.name);
11065            }
11066            final int NI = p.intents.size();
11067            int j;
11068            for (j = 0; j < NI; j++) {
11069                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11070                if (DEBUG_SHOW_INFO) {
11071                    Log.v(TAG, "    IntentFilter:");
11072                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11073                }
11074                removeFilter(intent);
11075            }
11076        }
11077
11078        @Override
11079        protected boolean allowFilterResult(
11080                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11081            ProviderInfo filterPi = filter.provider.info;
11082            for (int i = dest.size() - 1; i >= 0; i--) {
11083                ProviderInfo destPi = dest.get(i).providerInfo;
11084                if (destPi.name == filterPi.name
11085                        && destPi.packageName == filterPi.packageName) {
11086                    return false;
11087                }
11088            }
11089            return true;
11090        }
11091
11092        @Override
11093        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11094            return new PackageParser.ProviderIntentInfo[size];
11095        }
11096
11097        @Override
11098        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11099            if (!sUserManager.exists(userId))
11100                return true;
11101            PackageParser.Package p = filter.provider.owner;
11102            if (p != null) {
11103                PackageSetting ps = (PackageSetting) p.mExtras;
11104                if (ps != null) {
11105                    // System apps are never considered stopped for purposes of
11106                    // filtering, because there may be no way for the user to
11107                    // actually re-launch them.
11108                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11109                            && ps.getStopped(userId);
11110                }
11111            }
11112            return false;
11113        }
11114
11115        @Override
11116        protected boolean isPackageForFilter(String packageName,
11117                PackageParser.ProviderIntentInfo info) {
11118            return packageName.equals(info.provider.owner.packageName);
11119        }
11120
11121        @Override
11122        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11123                int match, int userId) {
11124            if (!sUserManager.exists(userId))
11125                return null;
11126            final PackageParser.ProviderIntentInfo info = filter;
11127            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11128                return null;
11129            }
11130            final PackageParser.Provider provider = info.provider;
11131            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11132            if (ps == null) {
11133                return null;
11134            }
11135            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11136                    ps.readUserState(userId), userId);
11137            if (pi == null) {
11138                return null;
11139            }
11140            final ResolveInfo res = new ResolveInfo();
11141            res.providerInfo = pi;
11142            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11143                res.filter = filter;
11144            }
11145            res.priority = info.getPriority();
11146            res.preferredOrder = provider.owner.mPreferredOrder;
11147            res.match = match;
11148            res.isDefault = info.hasDefault;
11149            res.labelRes = info.labelRes;
11150            res.nonLocalizedLabel = info.nonLocalizedLabel;
11151            res.icon = info.icon;
11152            res.system = res.providerInfo.applicationInfo.isSystemApp();
11153            return res;
11154        }
11155
11156        @Override
11157        protected void sortResults(List<ResolveInfo> results) {
11158            Collections.sort(results, mResolvePrioritySorter);
11159        }
11160
11161        @Override
11162        protected void dumpFilter(PrintWriter out, String prefix,
11163                PackageParser.ProviderIntentInfo filter) {
11164            out.print(prefix);
11165            out.print(
11166                    Integer.toHexString(System.identityHashCode(filter.provider)));
11167            out.print(' ');
11168            filter.provider.printComponentShortName(out);
11169            out.print(" filter ");
11170            out.println(Integer.toHexString(System.identityHashCode(filter)));
11171        }
11172
11173        @Override
11174        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11175            return filter.provider;
11176        }
11177
11178        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11179            PackageParser.Provider provider = (PackageParser.Provider)label;
11180            out.print(prefix); out.print(
11181                    Integer.toHexString(System.identityHashCode(provider)));
11182                    out.print(' ');
11183                    provider.printComponentShortName(out);
11184            if (count > 1) {
11185                out.print(" ("); out.print(count); out.print(" filters)");
11186            }
11187            out.println();
11188        }
11189
11190        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11191                = new ArrayMap<ComponentName, PackageParser.Provider>();
11192        private int mFlags;
11193    }
11194
11195    private static final class EphemeralIntentResolver
11196            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11197        @Override
11198        protected EphemeralResolveIntentInfo[] newArray(int size) {
11199            return new EphemeralResolveIntentInfo[size];
11200        }
11201
11202        @Override
11203        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11204            return true;
11205        }
11206
11207        @Override
11208        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11209                int userId) {
11210            if (!sUserManager.exists(userId)) {
11211                return null;
11212            }
11213            return info.getEphemeralResolveInfo();
11214        }
11215    }
11216
11217    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11218            new Comparator<ResolveInfo>() {
11219        public int compare(ResolveInfo r1, ResolveInfo r2) {
11220            int v1 = r1.priority;
11221            int v2 = r2.priority;
11222            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11223            if (v1 != v2) {
11224                return (v1 > v2) ? -1 : 1;
11225            }
11226            v1 = r1.preferredOrder;
11227            v2 = r2.preferredOrder;
11228            if (v1 != v2) {
11229                return (v1 > v2) ? -1 : 1;
11230            }
11231            if (r1.isDefault != r2.isDefault) {
11232                return r1.isDefault ? -1 : 1;
11233            }
11234            v1 = r1.match;
11235            v2 = r2.match;
11236            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11237            if (v1 != v2) {
11238                return (v1 > v2) ? -1 : 1;
11239            }
11240            if (r1.system != r2.system) {
11241                return r1.system ? -1 : 1;
11242            }
11243            if (r1.activityInfo != null) {
11244                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11245            }
11246            if (r1.serviceInfo != null) {
11247                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11248            }
11249            if (r1.providerInfo != null) {
11250                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11251            }
11252            return 0;
11253        }
11254    };
11255
11256    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11257            new Comparator<ProviderInfo>() {
11258        public int compare(ProviderInfo p1, ProviderInfo p2) {
11259            final int v1 = p1.initOrder;
11260            final int v2 = p2.initOrder;
11261            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11262        }
11263    };
11264
11265    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11266            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11267            final int[] userIds) {
11268        mHandler.post(new Runnable() {
11269            @Override
11270            public void run() {
11271                try {
11272                    final IActivityManager am = ActivityManagerNative.getDefault();
11273                    if (am == null) return;
11274                    final int[] resolvedUserIds;
11275                    if (userIds == null) {
11276                        resolvedUserIds = am.getRunningUserIds();
11277                    } else {
11278                        resolvedUserIds = userIds;
11279                    }
11280                    for (int id : resolvedUserIds) {
11281                        final Intent intent = new Intent(action,
11282                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11283                        if (extras != null) {
11284                            intent.putExtras(extras);
11285                        }
11286                        if (targetPkg != null) {
11287                            intent.setPackage(targetPkg);
11288                        }
11289                        // Modify the UID when posting to other users
11290                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11291                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11292                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11293                            intent.putExtra(Intent.EXTRA_UID, uid);
11294                        }
11295                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11296                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11297                        if (DEBUG_BROADCASTS) {
11298                            RuntimeException here = new RuntimeException("here");
11299                            here.fillInStackTrace();
11300                            Slog.d(TAG, "Sending to user " + id + ": "
11301                                    + intent.toShortString(false, true, false, false)
11302                                    + " " + intent.getExtras(), here);
11303                        }
11304                        am.broadcastIntent(null, intent, null, finishedReceiver,
11305                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11306                                null, finishedReceiver != null, false, id);
11307                    }
11308                } catch (RemoteException ex) {
11309                }
11310            }
11311        });
11312    }
11313
11314    /**
11315     * Check if the external storage media is available. This is true if there
11316     * is a mounted external storage medium or if the external storage is
11317     * emulated.
11318     */
11319    private boolean isExternalMediaAvailable() {
11320        return mMediaMounted || Environment.isExternalStorageEmulated();
11321    }
11322
11323    @Override
11324    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11325        // writer
11326        synchronized (mPackages) {
11327            if (!isExternalMediaAvailable()) {
11328                // If the external storage is no longer mounted at this point,
11329                // the caller may not have been able to delete all of this
11330                // packages files and can not delete any more.  Bail.
11331                return null;
11332            }
11333            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11334            if (lastPackage != null) {
11335                pkgs.remove(lastPackage);
11336            }
11337            if (pkgs.size() > 0) {
11338                return pkgs.get(0);
11339            }
11340        }
11341        return null;
11342    }
11343
11344    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11345        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11346                userId, andCode ? 1 : 0, packageName);
11347        if (mSystemReady) {
11348            msg.sendToTarget();
11349        } else {
11350            if (mPostSystemReadyMessages == null) {
11351                mPostSystemReadyMessages = new ArrayList<>();
11352            }
11353            mPostSystemReadyMessages.add(msg);
11354        }
11355    }
11356
11357    void startCleaningPackages() {
11358        // reader
11359        if (!isExternalMediaAvailable()) {
11360            return;
11361        }
11362        synchronized (mPackages) {
11363            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11364                return;
11365            }
11366        }
11367        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11368        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11369        IActivityManager am = ActivityManagerNative.getDefault();
11370        if (am != null) {
11371            try {
11372                am.startService(null, intent, null, mContext.getOpPackageName(),
11373                        UserHandle.USER_SYSTEM);
11374            } catch (RemoteException e) {
11375            }
11376        }
11377    }
11378
11379    @Override
11380    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11381            int installFlags, String installerPackageName, int userId) {
11382        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11383
11384        final int callingUid = Binder.getCallingUid();
11385        enforceCrossUserPermission(callingUid, userId,
11386                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11387
11388        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11389            try {
11390                if (observer != null) {
11391                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11392                }
11393            } catch (RemoteException re) {
11394            }
11395            return;
11396        }
11397
11398        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11399            installFlags |= PackageManager.INSTALL_FROM_ADB;
11400
11401        } else {
11402            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11403            // about installerPackageName.
11404
11405            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11406            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11407        }
11408
11409        UserHandle user;
11410        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11411            user = UserHandle.ALL;
11412        } else {
11413            user = new UserHandle(userId);
11414        }
11415
11416        // Only system components can circumvent runtime permissions when installing.
11417        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11418                && mContext.checkCallingOrSelfPermission(Manifest.permission
11419                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11420            throw new SecurityException("You need the "
11421                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11422                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11423        }
11424
11425        final File originFile = new File(originPath);
11426        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11427
11428        final Message msg = mHandler.obtainMessage(INIT_COPY);
11429        final VerificationInfo verificationInfo = new VerificationInfo(
11430                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11431        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11432                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11433                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11434                null /*certificates*/);
11435        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11436        msg.obj = params;
11437
11438        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11439                System.identityHashCode(msg.obj));
11440        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11441                System.identityHashCode(msg.obj));
11442
11443        mHandler.sendMessage(msg);
11444    }
11445
11446    void installStage(String packageName, File stagedDir, String stagedCid,
11447            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11448            String installerPackageName, int installerUid, UserHandle user,
11449            Certificate[][] certificates) {
11450        if (DEBUG_EPHEMERAL) {
11451            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11452                Slog.d(TAG, "Ephemeral install of " + packageName);
11453            }
11454        }
11455        final VerificationInfo verificationInfo = new VerificationInfo(
11456                sessionParams.originatingUri, sessionParams.referrerUri,
11457                sessionParams.originatingUid, installerUid);
11458
11459        final OriginInfo origin;
11460        if (stagedDir != null) {
11461            origin = OriginInfo.fromStagedFile(stagedDir);
11462        } else {
11463            origin = OriginInfo.fromStagedContainer(stagedCid);
11464        }
11465
11466        final Message msg = mHandler.obtainMessage(INIT_COPY);
11467        final InstallParams params = new InstallParams(origin, null, observer,
11468                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11469                verificationInfo, user, sessionParams.abiOverride,
11470                sessionParams.grantedRuntimePermissions, certificates);
11471        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11472        msg.obj = params;
11473
11474        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11475                System.identityHashCode(msg.obj));
11476        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11477                System.identityHashCode(msg.obj));
11478
11479        mHandler.sendMessage(msg);
11480    }
11481
11482    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11483            int userId) {
11484        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11485        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11486    }
11487
11488    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11489            int appId, int userId) {
11490        Bundle extras = new Bundle(1);
11491        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11492
11493        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11494                packageName, extras, 0, null, null, new int[] {userId});
11495        try {
11496            IActivityManager am = ActivityManagerNative.getDefault();
11497            if (isSystem && am.isUserRunning(userId, 0)) {
11498                // The just-installed/enabled app is bundled on the system, so presumed
11499                // to be able to run automatically without needing an explicit launch.
11500                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11501                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11502                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11503                        .setPackage(packageName);
11504                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11505                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11506            }
11507        } catch (RemoteException e) {
11508            // shouldn't happen
11509            Slog.w(TAG, "Unable to bootstrap installed package", e);
11510        }
11511    }
11512
11513    @Override
11514    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11515            int userId) {
11516        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11517        PackageSetting pkgSetting;
11518        final int uid = Binder.getCallingUid();
11519        enforceCrossUserPermission(uid, userId,
11520                true /* requireFullPermission */, true /* checkShell */,
11521                "setApplicationHiddenSetting for user " + userId);
11522
11523        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11524            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11525            return false;
11526        }
11527
11528        long callingId = Binder.clearCallingIdentity();
11529        try {
11530            boolean sendAdded = false;
11531            boolean sendRemoved = false;
11532            // writer
11533            synchronized (mPackages) {
11534                pkgSetting = mSettings.mPackages.get(packageName);
11535                if (pkgSetting == null) {
11536                    return false;
11537                }
11538                // Do not allow "android" is being disabled
11539                if ("android".equals(packageName)) {
11540                    Slog.w(TAG, "Cannot hide package: android");
11541                    return false;
11542                }
11543                // Only allow protected packages to hide themselves.
11544                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
11545                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11546                    Slog.w(TAG, "Not hiding protected package: " + packageName);
11547                    return false;
11548                }
11549
11550                if (pkgSetting.getHidden(userId) != hidden) {
11551                    pkgSetting.setHidden(hidden, userId);
11552                    mSettings.writePackageRestrictionsLPr(userId);
11553                    if (hidden) {
11554                        sendRemoved = true;
11555                    } else {
11556                        sendAdded = true;
11557                    }
11558                }
11559            }
11560            if (sendAdded) {
11561                sendPackageAddedForUser(packageName, pkgSetting, userId);
11562                return true;
11563            }
11564            if (sendRemoved) {
11565                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11566                        "hiding pkg");
11567                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11568                return true;
11569            }
11570        } finally {
11571            Binder.restoreCallingIdentity(callingId);
11572        }
11573        return false;
11574    }
11575
11576    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11577            int userId) {
11578        final PackageRemovedInfo info = new PackageRemovedInfo();
11579        info.removedPackage = packageName;
11580        info.removedUsers = new int[] {userId};
11581        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11582        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11583    }
11584
11585    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11586        if (pkgList.length > 0) {
11587            Bundle extras = new Bundle(1);
11588            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11589
11590            sendPackageBroadcast(
11591                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11592                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11593                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11594                    new int[] {userId});
11595        }
11596    }
11597
11598    /**
11599     * Returns true if application is not found or there was an error. Otherwise it returns
11600     * the hidden state of the package for the given user.
11601     */
11602    @Override
11603    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11604        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11605        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11606                true /* requireFullPermission */, false /* checkShell */,
11607                "getApplicationHidden for user " + userId);
11608        PackageSetting pkgSetting;
11609        long callingId = Binder.clearCallingIdentity();
11610        try {
11611            // writer
11612            synchronized (mPackages) {
11613                pkgSetting = mSettings.mPackages.get(packageName);
11614                if (pkgSetting == null) {
11615                    return true;
11616                }
11617                return pkgSetting.getHidden(userId);
11618            }
11619        } finally {
11620            Binder.restoreCallingIdentity(callingId);
11621        }
11622    }
11623
11624    /**
11625     * @hide
11626     */
11627    @Override
11628    public int installExistingPackageAsUser(String packageName, int userId) {
11629        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11630                null);
11631        PackageSetting pkgSetting;
11632        final int uid = Binder.getCallingUid();
11633        enforceCrossUserPermission(uid, userId,
11634                true /* requireFullPermission */, true /* checkShell */,
11635                "installExistingPackage for user " + userId);
11636        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11637            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11638        }
11639
11640        long callingId = Binder.clearCallingIdentity();
11641        try {
11642            boolean installed = false;
11643
11644            // writer
11645            synchronized (mPackages) {
11646                pkgSetting = mSettings.mPackages.get(packageName);
11647                if (pkgSetting == null) {
11648                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11649                }
11650                if (!pkgSetting.getInstalled(userId)) {
11651                    pkgSetting.setInstalled(true, userId);
11652                    pkgSetting.setHidden(false, userId);
11653                    mSettings.writePackageRestrictionsLPr(userId);
11654                    installed = true;
11655                }
11656            }
11657
11658            if (installed) {
11659                if (pkgSetting.pkg != null) {
11660                    synchronized (mInstallLock) {
11661                        // We don't need to freeze for a brand new install
11662                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11663                    }
11664                }
11665                sendPackageAddedForUser(packageName, pkgSetting, userId);
11666            }
11667        } finally {
11668            Binder.restoreCallingIdentity(callingId);
11669        }
11670
11671        return PackageManager.INSTALL_SUCCEEDED;
11672    }
11673
11674    boolean isUserRestricted(int userId, String restrictionKey) {
11675        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11676        if (restrictions.getBoolean(restrictionKey, false)) {
11677            Log.w(TAG, "User is restricted: " + restrictionKey);
11678            return true;
11679        }
11680        return false;
11681    }
11682
11683    @Override
11684    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11685            int userId) {
11686        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11687        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11688                true /* requireFullPermission */, true /* checkShell */,
11689                "setPackagesSuspended for user " + userId);
11690
11691        if (ArrayUtils.isEmpty(packageNames)) {
11692            return packageNames;
11693        }
11694
11695        // List of package names for whom the suspended state has changed.
11696        List<String> changedPackages = new ArrayList<>(packageNames.length);
11697        // List of package names for whom the suspended state is not set as requested in this
11698        // method.
11699        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11700        long callingId = Binder.clearCallingIdentity();
11701        try {
11702            for (int i = 0; i < packageNames.length; i++) {
11703                String packageName = packageNames[i];
11704                boolean changed = false;
11705                final int appId;
11706                synchronized (mPackages) {
11707                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11708                    if (pkgSetting == null) {
11709                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11710                                + "\". Skipping suspending/un-suspending.");
11711                        unactionedPackages.add(packageName);
11712                        continue;
11713                    }
11714                    appId = pkgSetting.appId;
11715                    if (pkgSetting.getSuspended(userId) != suspended) {
11716                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11717                            unactionedPackages.add(packageName);
11718                            continue;
11719                        }
11720                        pkgSetting.setSuspended(suspended, userId);
11721                        mSettings.writePackageRestrictionsLPr(userId);
11722                        changed = true;
11723                        changedPackages.add(packageName);
11724                    }
11725                }
11726
11727                if (changed && suspended) {
11728                    killApplication(packageName, UserHandle.getUid(userId, appId),
11729                            "suspending package");
11730                }
11731            }
11732        } finally {
11733            Binder.restoreCallingIdentity(callingId);
11734        }
11735
11736        if (!changedPackages.isEmpty()) {
11737            sendPackagesSuspendedForUser(changedPackages.toArray(
11738                    new String[changedPackages.size()]), userId, suspended);
11739        }
11740
11741        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11742    }
11743
11744    @Override
11745    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11746        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11747                true /* requireFullPermission */, false /* checkShell */,
11748                "isPackageSuspendedForUser for user " + userId);
11749        synchronized (mPackages) {
11750            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11751            if (pkgSetting == null) {
11752                throw new IllegalArgumentException("Unknown target package: " + packageName);
11753            }
11754            return pkgSetting.getSuspended(userId);
11755        }
11756    }
11757
11758    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11759        if (isPackageDeviceAdmin(packageName, userId)) {
11760            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11761                    + "\": has an active device admin");
11762            return false;
11763        }
11764
11765        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11766        if (packageName.equals(activeLauncherPackageName)) {
11767            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11768                    + "\": contains the active launcher");
11769            return false;
11770        }
11771
11772        if (packageName.equals(mRequiredInstallerPackage)) {
11773            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11774                    + "\": required for package installation");
11775            return false;
11776        }
11777
11778        if (packageName.equals(mRequiredVerifierPackage)) {
11779            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11780                    + "\": required for package verification");
11781            return false;
11782        }
11783
11784        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11785            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11786                    + "\": is the default dialer");
11787            return false;
11788        }
11789
11790        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
11791            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11792                    + "\": protected package");
11793            return false;
11794        }
11795
11796        return true;
11797    }
11798
11799    private String getActiveLauncherPackageName(int userId) {
11800        Intent intent = new Intent(Intent.ACTION_MAIN);
11801        intent.addCategory(Intent.CATEGORY_HOME);
11802        ResolveInfo resolveInfo = resolveIntent(
11803                intent,
11804                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11805                PackageManager.MATCH_DEFAULT_ONLY,
11806                userId);
11807
11808        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11809    }
11810
11811    private String getDefaultDialerPackageName(int userId) {
11812        synchronized (mPackages) {
11813            return mSettings.getDefaultDialerPackageNameLPw(userId);
11814        }
11815    }
11816
11817    @Override
11818    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11819        mContext.enforceCallingOrSelfPermission(
11820                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11821                "Only package verification agents can verify applications");
11822
11823        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11824        final PackageVerificationResponse response = new PackageVerificationResponse(
11825                verificationCode, Binder.getCallingUid());
11826        msg.arg1 = id;
11827        msg.obj = response;
11828        mHandler.sendMessage(msg);
11829    }
11830
11831    @Override
11832    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11833            long millisecondsToDelay) {
11834        mContext.enforceCallingOrSelfPermission(
11835                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11836                "Only package verification agents can extend verification timeouts");
11837
11838        final PackageVerificationState state = mPendingVerification.get(id);
11839        final PackageVerificationResponse response = new PackageVerificationResponse(
11840                verificationCodeAtTimeout, Binder.getCallingUid());
11841
11842        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11843            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11844        }
11845        if (millisecondsToDelay < 0) {
11846            millisecondsToDelay = 0;
11847        }
11848        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11849                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11850            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11851        }
11852
11853        if ((state != null) && !state.timeoutExtended()) {
11854            state.extendTimeout();
11855
11856            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11857            msg.arg1 = id;
11858            msg.obj = response;
11859            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11860        }
11861    }
11862
11863    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11864            int verificationCode, UserHandle user) {
11865        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11866        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11867        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11868        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11869        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11870
11871        mContext.sendBroadcastAsUser(intent, user,
11872                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11873    }
11874
11875    private ComponentName matchComponentForVerifier(String packageName,
11876            List<ResolveInfo> receivers) {
11877        ActivityInfo targetReceiver = null;
11878
11879        final int NR = receivers.size();
11880        for (int i = 0; i < NR; i++) {
11881            final ResolveInfo info = receivers.get(i);
11882            if (info.activityInfo == null) {
11883                continue;
11884            }
11885
11886            if (packageName.equals(info.activityInfo.packageName)) {
11887                targetReceiver = info.activityInfo;
11888                break;
11889            }
11890        }
11891
11892        if (targetReceiver == null) {
11893            return null;
11894        }
11895
11896        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11897    }
11898
11899    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11900            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11901        if (pkgInfo.verifiers.length == 0) {
11902            return null;
11903        }
11904
11905        final int N = pkgInfo.verifiers.length;
11906        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11907        for (int i = 0; i < N; i++) {
11908            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11909
11910            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11911                    receivers);
11912            if (comp == null) {
11913                continue;
11914            }
11915
11916            final int verifierUid = getUidForVerifier(verifierInfo);
11917            if (verifierUid == -1) {
11918                continue;
11919            }
11920
11921            if (DEBUG_VERIFY) {
11922                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11923                        + " with the correct signature");
11924            }
11925            sufficientVerifiers.add(comp);
11926            verificationState.addSufficientVerifier(verifierUid);
11927        }
11928
11929        return sufficientVerifiers;
11930    }
11931
11932    private int getUidForVerifier(VerifierInfo verifierInfo) {
11933        synchronized (mPackages) {
11934            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11935            if (pkg == null) {
11936                return -1;
11937            } else if (pkg.mSignatures.length != 1) {
11938                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11939                        + " has more than one signature; ignoring");
11940                return -1;
11941            }
11942
11943            /*
11944             * If the public key of the package's signature does not match
11945             * our expected public key, then this is a different package and
11946             * we should skip.
11947             */
11948
11949            final byte[] expectedPublicKey;
11950            try {
11951                final Signature verifierSig = pkg.mSignatures[0];
11952                final PublicKey publicKey = verifierSig.getPublicKey();
11953                expectedPublicKey = publicKey.getEncoded();
11954            } catch (CertificateException e) {
11955                return -1;
11956            }
11957
11958            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11959
11960            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11961                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11962                        + " does not have the expected public key; ignoring");
11963                return -1;
11964            }
11965
11966            return pkg.applicationInfo.uid;
11967        }
11968    }
11969
11970    @Override
11971    public void finishPackageInstall(int token, boolean didLaunch) {
11972        enforceSystemOrRoot("Only the system is allowed to finish installs");
11973
11974        if (DEBUG_INSTALL) {
11975            Slog.v(TAG, "BM finishing package install for " + token);
11976        }
11977        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11978
11979        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
11980        mHandler.sendMessage(msg);
11981    }
11982
11983    /**
11984     * Get the verification agent timeout.
11985     *
11986     * @return verification timeout in milliseconds
11987     */
11988    private long getVerificationTimeout() {
11989        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11990                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11991                DEFAULT_VERIFICATION_TIMEOUT);
11992    }
11993
11994    /**
11995     * Get the default verification agent response code.
11996     *
11997     * @return default verification response code
11998     */
11999    private int getDefaultVerificationResponse() {
12000        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12001                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12002                DEFAULT_VERIFICATION_RESPONSE);
12003    }
12004
12005    /**
12006     * Check whether or not package verification has been enabled.
12007     *
12008     * @return true if verification should be performed
12009     */
12010    private boolean isVerificationEnabled(int userId, int installFlags) {
12011        if (!DEFAULT_VERIFY_ENABLE) {
12012            return false;
12013        }
12014        // Ephemeral apps don't get the full verification treatment
12015        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12016            if (DEBUG_EPHEMERAL) {
12017                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12018            }
12019            return false;
12020        }
12021
12022        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12023
12024        // Check if installing from ADB
12025        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12026            // Do not run verification in a test harness environment
12027            if (ActivityManager.isRunningInTestHarness()) {
12028                return false;
12029            }
12030            if (ensureVerifyAppsEnabled) {
12031                return true;
12032            }
12033            // Check if the developer does not want package verification for ADB installs
12034            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12035                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12036                return false;
12037            }
12038        }
12039
12040        if (ensureVerifyAppsEnabled) {
12041            return true;
12042        }
12043
12044        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12045                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12046    }
12047
12048    @Override
12049    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12050            throws RemoteException {
12051        mContext.enforceCallingOrSelfPermission(
12052                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12053                "Only intentfilter verification agents can verify applications");
12054
12055        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12056        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12057                Binder.getCallingUid(), verificationCode, failedDomains);
12058        msg.arg1 = id;
12059        msg.obj = response;
12060        mHandler.sendMessage(msg);
12061    }
12062
12063    @Override
12064    public int getIntentVerificationStatus(String packageName, int userId) {
12065        synchronized (mPackages) {
12066            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12067        }
12068    }
12069
12070    @Override
12071    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12072        mContext.enforceCallingOrSelfPermission(
12073                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12074
12075        boolean result = false;
12076        synchronized (mPackages) {
12077            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12078        }
12079        if (result) {
12080            scheduleWritePackageRestrictionsLocked(userId);
12081        }
12082        return result;
12083    }
12084
12085    @Override
12086    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12087            String packageName) {
12088        synchronized (mPackages) {
12089            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12090        }
12091    }
12092
12093    @Override
12094    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12095        if (TextUtils.isEmpty(packageName)) {
12096            return ParceledListSlice.emptyList();
12097        }
12098        synchronized (mPackages) {
12099            PackageParser.Package pkg = mPackages.get(packageName);
12100            if (pkg == null || pkg.activities == null) {
12101                return ParceledListSlice.emptyList();
12102            }
12103            final int count = pkg.activities.size();
12104            ArrayList<IntentFilter> result = new ArrayList<>();
12105            for (int n=0; n<count; n++) {
12106                PackageParser.Activity activity = pkg.activities.get(n);
12107                if (activity.intents != null && activity.intents.size() > 0) {
12108                    result.addAll(activity.intents);
12109                }
12110            }
12111            return new ParceledListSlice<>(result);
12112        }
12113    }
12114
12115    @Override
12116    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12117        mContext.enforceCallingOrSelfPermission(
12118                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12119
12120        synchronized (mPackages) {
12121            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12122            if (packageName != null) {
12123                result |= updateIntentVerificationStatus(packageName,
12124                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12125                        userId);
12126                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12127                        packageName, userId);
12128            }
12129            return result;
12130        }
12131    }
12132
12133    @Override
12134    public String getDefaultBrowserPackageName(int userId) {
12135        synchronized (mPackages) {
12136            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12137        }
12138    }
12139
12140    /**
12141     * Get the "allow unknown sources" setting.
12142     *
12143     * @return the current "allow unknown sources" setting
12144     */
12145    private int getUnknownSourcesSettings() {
12146        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12147                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12148                -1);
12149    }
12150
12151    @Override
12152    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12153        final int uid = Binder.getCallingUid();
12154        // writer
12155        synchronized (mPackages) {
12156            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12157            if (targetPackageSetting == null) {
12158                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12159            }
12160
12161            PackageSetting installerPackageSetting;
12162            if (installerPackageName != null) {
12163                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12164                if (installerPackageSetting == null) {
12165                    throw new IllegalArgumentException("Unknown installer package: "
12166                            + installerPackageName);
12167                }
12168            } else {
12169                installerPackageSetting = null;
12170            }
12171
12172            Signature[] callerSignature;
12173            Object obj = mSettings.getUserIdLPr(uid);
12174            if (obj != null) {
12175                if (obj instanceof SharedUserSetting) {
12176                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12177                } else if (obj instanceof PackageSetting) {
12178                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12179                } else {
12180                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12181                }
12182            } else {
12183                throw new SecurityException("Unknown calling UID: " + uid);
12184            }
12185
12186            // Verify: can't set installerPackageName to a package that is
12187            // not signed with the same cert as the caller.
12188            if (installerPackageSetting != null) {
12189                if (compareSignatures(callerSignature,
12190                        installerPackageSetting.signatures.mSignatures)
12191                        != PackageManager.SIGNATURE_MATCH) {
12192                    throw new SecurityException(
12193                            "Caller does not have same cert as new installer package "
12194                            + installerPackageName);
12195                }
12196            }
12197
12198            // Verify: if target already has an installer package, it must
12199            // be signed with the same cert as the caller.
12200            if (targetPackageSetting.installerPackageName != null) {
12201                PackageSetting setting = mSettings.mPackages.get(
12202                        targetPackageSetting.installerPackageName);
12203                // If the currently set package isn't valid, then it's always
12204                // okay to change it.
12205                if (setting != null) {
12206                    if (compareSignatures(callerSignature,
12207                            setting.signatures.mSignatures)
12208                            != PackageManager.SIGNATURE_MATCH) {
12209                        throw new SecurityException(
12210                                "Caller does not have same cert as old installer package "
12211                                + targetPackageSetting.installerPackageName);
12212                    }
12213                }
12214            }
12215
12216            // Okay!
12217            targetPackageSetting.installerPackageName = installerPackageName;
12218            if (installerPackageName != null) {
12219                mSettings.mInstallerPackages.add(installerPackageName);
12220            }
12221            scheduleWriteSettingsLocked();
12222        }
12223    }
12224
12225    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12226        // Queue up an async operation since the package installation may take a little while.
12227        mHandler.post(new Runnable() {
12228            public void run() {
12229                mHandler.removeCallbacks(this);
12230                 // Result object to be returned
12231                PackageInstalledInfo res = new PackageInstalledInfo();
12232                res.setReturnCode(currentStatus);
12233                res.uid = -1;
12234                res.pkg = null;
12235                res.removedInfo = null;
12236                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12237                    args.doPreInstall(res.returnCode);
12238                    synchronized (mInstallLock) {
12239                        installPackageTracedLI(args, res);
12240                    }
12241                    args.doPostInstall(res.returnCode, res.uid);
12242                }
12243
12244                // A restore should be performed at this point if (a) the install
12245                // succeeded, (b) the operation is not an update, and (c) the new
12246                // package has not opted out of backup participation.
12247                final boolean update = res.removedInfo != null
12248                        && res.removedInfo.removedPackage != null;
12249                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12250                boolean doRestore = !update
12251                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12252
12253                // Set up the post-install work request bookkeeping.  This will be used
12254                // and cleaned up by the post-install event handling regardless of whether
12255                // there's a restore pass performed.  Token values are >= 1.
12256                int token;
12257                if (mNextInstallToken < 0) mNextInstallToken = 1;
12258                token = mNextInstallToken++;
12259
12260                PostInstallData data = new PostInstallData(args, res);
12261                mRunningInstalls.put(token, data);
12262                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12263
12264                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12265                    // Pass responsibility to the Backup Manager.  It will perform a
12266                    // restore if appropriate, then pass responsibility back to the
12267                    // Package Manager to run the post-install observer callbacks
12268                    // and broadcasts.
12269                    IBackupManager bm = IBackupManager.Stub.asInterface(
12270                            ServiceManager.getService(Context.BACKUP_SERVICE));
12271                    if (bm != null) {
12272                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12273                                + " to BM for possible restore");
12274                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12275                        try {
12276                            // TODO: http://b/22388012
12277                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12278                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12279                            } else {
12280                                doRestore = false;
12281                            }
12282                        } catch (RemoteException e) {
12283                            // can't happen; the backup manager is local
12284                        } catch (Exception e) {
12285                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12286                            doRestore = false;
12287                        }
12288                    } else {
12289                        Slog.e(TAG, "Backup Manager not found!");
12290                        doRestore = false;
12291                    }
12292                }
12293
12294                if (!doRestore) {
12295                    // No restore possible, or the Backup Manager was mysteriously not
12296                    // available -- just fire the post-install work request directly.
12297                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12298
12299                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12300
12301                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12302                    mHandler.sendMessage(msg);
12303                }
12304            }
12305        });
12306    }
12307
12308    /**
12309     * Callback from PackageSettings whenever an app is first transitioned out of the
12310     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12311     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12312     * here whether the app is the target of an ongoing install, and only send the
12313     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12314     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12315     * handling.
12316     */
12317    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12318        // Serialize this with the rest of the install-process message chain.  In the
12319        // restore-at-install case, this Runnable will necessarily run before the
12320        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12321        // are coherent.  In the non-restore case, the app has already completed install
12322        // and been launched through some other means, so it is not in a problematic
12323        // state for observers to see the FIRST_LAUNCH signal.
12324        mHandler.post(new Runnable() {
12325            @Override
12326            public void run() {
12327                for (int i = 0; i < mRunningInstalls.size(); i++) {
12328                    final PostInstallData data = mRunningInstalls.valueAt(i);
12329                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12330                        // right package; but is it for the right user?
12331                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12332                            if (userId == data.res.newUsers[uIndex]) {
12333                                if (DEBUG_BACKUP) {
12334                                    Slog.i(TAG, "Package " + pkgName
12335                                            + " being restored so deferring FIRST_LAUNCH");
12336                                }
12337                                return;
12338                            }
12339                        }
12340                    }
12341                }
12342                // didn't find it, so not being restored
12343                if (DEBUG_BACKUP) {
12344                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12345                }
12346                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12347            }
12348        });
12349    }
12350
12351    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12352        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12353                installerPkg, null, userIds);
12354    }
12355
12356    private abstract class HandlerParams {
12357        private static final int MAX_RETRIES = 4;
12358
12359        /**
12360         * Number of times startCopy() has been attempted and had a non-fatal
12361         * error.
12362         */
12363        private int mRetries = 0;
12364
12365        /** User handle for the user requesting the information or installation. */
12366        private final UserHandle mUser;
12367        String traceMethod;
12368        int traceCookie;
12369
12370        HandlerParams(UserHandle user) {
12371            mUser = user;
12372        }
12373
12374        UserHandle getUser() {
12375            return mUser;
12376        }
12377
12378        HandlerParams setTraceMethod(String traceMethod) {
12379            this.traceMethod = traceMethod;
12380            return this;
12381        }
12382
12383        HandlerParams setTraceCookie(int traceCookie) {
12384            this.traceCookie = traceCookie;
12385            return this;
12386        }
12387
12388        final boolean startCopy() {
12389            boolean res;
12390            try {
12391                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12392
12393                if (++mRetries > MAX_RETRIES) {
12394                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12395                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12396                    handleServiceError();
12397                    return false;
12398                } else {
12399                    handleStartCopy();
12400                    res = true;
12401                }
12402            } catch (RemoteException e) {
12403                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12404                mHandler.sendEmptyMessage(MCS_RECONNECT);
12405                res = false;
12406            }
12407            handleReturnCode();
12408            return res;
12409        }
12410
12411        final void serviceError() {
12412            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12413            handleServiceError();
12414            handleReturnCode();
12415        }
12416
12417        abstract void handleStartCopy() throws RemoteException;
12418        abstract void handleServiceError();
12419        abstract void handleReturnCode();
12420    }
12421
12422    class MeasureParams extends HandlerParams {
12423        private final PackageStats mStats;
12424        private boolean mSuccess;
12425
12426        private final IPackageStatsObserver mObserver;
12427
12428        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12429            super(new UserHandle(stats.userHandle));
12430            mObserver = observer;
12431            mStats = stats;
12432        }
12433
12434        @Override
12435        public String toString() {
12436            return "MeasureParams{"
12437                + Integer.toHexString(System.identityHashCode(this))
12438                + " " + mStats.packageName + "}";
12439        }
12440
12441        @Override
12442        void handleStartCopy() throws RemoteException {
12443            synchronized (mInstallLock) {
12444                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12445            }
12446
12447            if (mSuccess) {
12448                boolean mounted = false;
12449                try {
12450                    final String status = Environment.getExternalStorageState();
12451                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12452                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12453                } catch (Exception e) {
12454                }
12455
12456                if (mounted) {
12457                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12458
12459                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12460                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12461
12462                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12463                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12464
12465                    // Always subtract cache size, since it's a subdirectory
12466                    mStats.externalDataSize -= mStats.externalCacheSize;
12467
12468                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12469                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12470
12471                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12472                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12473                }
12474            }
12475        }
12476
12477        @Override
12478        void handleReturnCode() {
12479            if (mObserver != null) {
12480                try {
12481                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12482                } catch (RemoteException e) {
12483                    Slog.i(TAG, "Observer no longer exists.");
12484                }
12485            }
12486        }
12487
12488        @Override
12489        void handleServiceError() {
12490            Slog.e(TAG, "Could not measure application " + mStats.packageName
12491                            + " external storage");
12492        }
12493    }
12494
12495    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12496            throws RemoteException {
12497        long result = 0;
12498        for (File path : paths) {
12499            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12500        }
12501        return result;
12502    }
12503
12504    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12505        for (File path : paths) {
12506            try {
12507                mcs.clearDirectory(path.getAbsolutePath());
12508            } catch (RemoteException e) {
12509            }
12510        }
12511    }
12512
12513    static class OriginInfo {
12514        /**
12515         * Location where install is coming from, before it has been
12516         * copied/renamed into place. This could be a single monolithic APK
12517         * file, or a cluster directory. This location may be untrusted.
12518         */
12519        final File file;
12520        final String cid;
12521
12522        /**
12523         * Flag indicating that {@link #file} or {@link #cid} has already been
12524         * staged, meaning downstream users don't need to defensively copy the
12525         * contents.
12526         */
12527        final boolean staged;
12528
12529        /**
12530         * Flag indicating that {@link #file} or {@link #cid} is an already
12531         * installed app that is being moved.
12532         */
12533        final boolean existing;
12534
12535        final String resolvedPath;
12536        final File resolvedFile;
12537
12538        static OriginInfo fromNothing() {
12539            return new OriginInfo(null, null, false, false);
12540        }
12541
12542        static OriginInfo fromUntrustedFile(File file) {
12543            return new OriginInfo(file, null, false, false);
12544        }
12545
12546        static OriginInfo fromExistingFile(File file) {
12547            return new OriginInfo(file, null, false, true);
12548        }
12549
12550        static OriginInfo fromStagedFile(File file) {
12551            return new OriginInfo(file, null, true, false);
12552        }
12553
12554        static OriginInfo fromStagedContainer(String cid) {
12555            return new OriginInfo(null, cid, true, false);
12556        }
12557
12558        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12559            this.file = file;
12560            this.cid = cid;
12561            this.staged = staged;
12562            this.existing = existing;
12563
12564            if (cid != null) {
12565                resolvedPath = PackageHelper.getSdDir(cid);
12566                resolvedFile = new File(resolvedPath);
12567            } else if (file != null) {
12568                resolvedPath = file.getAbsolutePath();
12569                resolvedFile = file;
12570            } else {
12571                resolvedPath = null;
12572                resolvedFile = null;
12573            }
12574        }
12575    }
12576
12577    static class MoveInfo {
12578        final int moveId;
12579        final String fromUuid;
12580        final String toUuid;
12581        final String packageName;
12582        final String dataAppName;
12583        final int appId;
12584        final String seinfo;
12585        final int targetSdkVersion;
12586
12587        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12588                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12589            this.moveId = moveId;
12590            this.fromUuid = fromUuid;
12591            this.toUuid = toUuid;
12592            this.packageName = packageName;
12593            this.dataAppName = dataAppName;
12594            this.appId = appId;
12595            this.seinfo = seinfo;
12596            this.targetSdkVersion = targetSdkVersion;
12597        }
12598    }
12599
12600    static class VerificationInfo {
12601        /** A constant used to indicate that a uid value is not present. */
12602        public static final int NO_UID = -1;
12603
12604        /** URI referencing where the package was downloaded from. */
12605        final Uri originatingUri;
12606
12607        /** HTTP referrer URI associated with the originatingURI. */
12608        final Uri referrer;
12609
12610        /** UID of the application that the install request originated from. */
12611        final int originatingUid;
12612
12613        /** UID of application requesting the install */
12614        final int installerUid;
12615
12616        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12617            this.originatingUri = originatingUri;
12618            this.referrer = referrer;
12619            this.originatingUid = originatingUid;
12620            this.installerUid = installerUid;
12621        }
12622    }
12623
12624    class InstallParams extends HandlerParams {
12625        final OriginInfo origin;
12626        final MoveInfo move;
12627        final IPackageInstallObserver2 observer;
12628        int installFlags;
12629        final String installerPackageName;
12630        final String volumeUuid;
12631        private InstallArgs mArgs;
12632        private int mRet;
12633        final String packageAbiOverride;
12634        final String[] grantedRuntimePermissions;
12635        final VerificationInfo verificationInfo;
12636        final Certificate[][] certificates;
12637
12638        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12639                int installFlags, String installerPackageName, String volumeUuid,
12640                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12641                String[] grantedPermissions, Certificate[][] certificates) {
12642            super(user);
12643            this.origin = origin;
12644            this.move = move;
12645            this.observer = observer;
12646            this.installFlags = installFlags;
12647            this.installerPackageName = installerPackageName;
12648            this.volumeUuid = volumeUuid;
12649            this.verificationInfo = verificationInfo;
12650            this.packageAbiOverride = packageAbiOverride;
12651            this.grantedRuntimePermissions = grantedPermissions;
12652            this.certificates = certificates;
12653        }
12654
12655        @Override
12656        public String toString() {
12657            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12658                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12659        }
12660
12661        private int installLocationPolicy(PackageInfoLite pkgLite) {
12662            String packageName = pkgLite.packageName;
12663            int installLocation = pkgLite.installLocation;
12664            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12665            // reader
12666            synchronized (mPackages) {
12667                // Currently installed package which the new package is attempting to replace or
12668                // null if no such package is installed.
12669                PackageParser.Package installedPkg = mPackages.get(packageName);
12670                // Package which currently owns the data which the new package will own if installed.
12671                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12672                // will be null whereas dataOwnerPkg will contain information about the package
12673                // which was uninstalled while keeping its data.
12674                PackageParser.Package dataOwnerPkg = installedPkg;
12675                if (dataOwnerPkg  == null) {
12676                    PackageSetting ps = mSettings.mPackages.get(packageName);
12677                    if (ps != null) {
12678                        dataOwnerPkg = ps.pkg;
12679                    }
12680                }
12681
12682                if (dataOwnerPkg != null) {
12683                    // If installed, the package will get access to data left on the device by its
12684                    // predecessor. As a security measure, this is permited only if this is not a
12685                    // version downgrade or if the predecessor package is marked as debuggable and
12686                    // a downgrade is explicitly requested.
12687                    //
12688                    // On debuggable platform builds, downgrades are permitted even for
12689                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12690                    // not offer security guarantees and thus it's OK to disable some security
12691                    // mechanisms to make debugging/testing easier on those builds. However, even on
12692                    // debuggable builds downgrades of packages are permitted only if requested via
12693                    // installFlags. This is because we aim to keep the behavior of debuggable
12694                    // platform builds as close as possible to the behavior of non-debuggable
12695                    // platform builds.
12696                    final boolean downgradeRequested =
12697                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12698                    final boolean packageDebuggable =
12699                                (dataOwnerPkg.applicationInfo.flags
12700                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12701                    final boolean downgradePermitted =
12702                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12703                    if (!downgradePermitted) {
12704                        try {
12705                            checkDowngrade(dataOwnerPkg, pkgLite);
12706                        } catch (PackageManagerException e) {
12707                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12708                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12709                        }
12710                    }
12711                }
12712
12713                if (installedPkg != null) {
12714                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12715                        // Check for updated system application.
12716                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12717                            if (onSd) {
12718                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12719                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12720                            }
12721                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12722                        } else {
12723                            if (onSd) {
12724                                // Install flag overrides everything.
12725                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12726                            }
12727                            // If current upgrade specifies particular preference
12728                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12729                                // Application explicitly specified internal.
12730                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12731                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12732                                // App explictly prefers external. Let policy decide
12733                            } else {
12734                                // Prefer previous location
12735                                if (isExternal(installedPkg)) {
12736                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12737                                }
12738                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12739                            }
12740                        }
12741                    } else {
12742                        // Invalid install. Return error code
12743                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12744                    }
12745                }
12746            }
12747            // All the special cases have been taken care of.
12748            // Return result based on recommended install location.
12749            if (onSd) {
12750                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12751            }
12752            return pkgLite.recommendedInstallLocation;
12753        }
12754
12755        /*
12756         * Invoke remote method to get package information and install
12757         * location values. Override install location based on default
12758         * policy if needed and then create install arguments based
12759         * on the install location.
12760         */
12761        public void handleStartCopy() throws RemoteException {
12762            int ret = PackageManager.INSTALL_SUCCEEDED;
12763
12764            // If we're already staged, we've firmly committed to an install location
12765            if (origin.staged) {
12766                if (origin.file != null) {
12767                    installFlags |= PackageManager.INSTALL_INTERNAL;
12768                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12769                } else if (origin.cid != null) {
12770                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12771                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12772                } else {
12773                    throw new IllegalStateException("Invalid stage location");
12774                }
12775            }
12776
12777            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12778            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12779            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12780            PackageInfoLite pkgLite = null;
12781
12782            if (onInt && onSd) {
12783                // Check if both bits are set.
12784                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12785                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12786            } else if (onSd && ephemeral) {
12787                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12788                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12789            } else {
12790                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12791                        packageAbiOverride);
12792
12793                if (DEBUG_EPHEMERAL && ephemeral) {
12794                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12795                }
12796
12797                /*
12798                 * If we have too little free space, try to free cache
12799                 * before giving up.
12800                 */
12801                if (!origin.staged && pkgLite.recommendedInstallLocation
12802                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12803                    // TODO: focus freeing disk space on the target device
12804                    final StorageManager storage = StorageManager.from(mContext);
12805                    final long lowThreshold = storage.getStorageLowBytes(
12806                            Environment.getDataDirectory());
12807
12808                    final long sizeBytes = mContainerService.calculateInstalledSize(
12809                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12810
12811                    try {
12812                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12813                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12814                                installFlags, packageAbiOverride);
12815                    } catch (InstallerException e) {
12816                        Slog.w(TAG, "Failed to free cache", e);
12817                    }
12818
12819                    /*
12820                     * The cache free must have deleted the file we
12821                     * downloaded to install.
12822                     *
12823                     * TODO: fix the "freeCache" call to not delete
12824                     *       the file we care about.
12825                     */
12826                    if (pkgLite.recommendedInstallLocation
12827                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12828                        pkgLite.recommendedInstallLocation
12829                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12830                    }
12831                }
12832            }
12833
12834            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12835                int loc = pkgLite.recommendedInstallLocation;
12836                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12837                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12838                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12839                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12840                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12841                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12842                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12843                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12844                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12845                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12846                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12847                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12848                } else {
12849                    // Override with defaults if needed.
12850                    loc = installLocationPolicy(pkgLite);
12851                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12852                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12853                    } else if (!onSd && !onInt) {
12854                        // Override install location with flags
12855                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12856                            // Set the flag to install on external media.
12857                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12858                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12859                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12860                            if (DEBUG_EPHEMERAL) {
12861                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12862                            }
12863                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12864                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12865                                    |PackageManager.INSTALL_INTERNAL);
12866                        } else {
12867                            // Make sure the flag for installing on external
12868                            // media is unset
12869                            installFlags |= PackageManager.INSTALL_INTERNAL;
12870                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12871                        }
12872                    }
12873                }
12874            }
12875
12876            final InstallArgs args = createInstallArgs(this);
12877            mArgs = args;
12878
12879            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12880                // TODO: http://b/22976637
12881                // Apps installed for "all" users use the device owner to verify the app
12882                UserHandle verifierUser = getUser();
12883                if (verifierUser == UserHandle.ALL) {
12884                    verifierUser = UserHandle.SYSTEM;
12885                }
12886
12887                /*
12888                 * Determine if we have any installed package verifiers. If we
12889                 * do, then we'll defer to them to verify the packages.
12890                 */
12891                final int requiredUid = mRequiredVerifierPackage == null ? -1
12892                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12893                                verifierUser.getIdentifier());
12894                if (!origin.existing && requiredUid != -1
12895                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12896                    final Intent verification = new Intent(
12897                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12898                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12899                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12900                            PACKAGE_MIME_TYPE);
12901                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12902
12903                    // Query all live verifiers based on current user state
12904                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12905                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12906
12907                    if (DEBUG_VERIFY) {
12908                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12909                                + verification.toString() + " with " + pkgLite.verifiers.length
12910                                + " optional verifiers");
12911                    }
12912
12913                    final int verificationId = mPendingVerificationToken++;
12914
12915                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12916
12917                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12918                            installerPackageName);
12919
12920                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12921                            installFlags);
12922
12923                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12924                            pkgLite.packageName);
12925
12926                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12927                            pkgLite.versionCode);
12928
12929                    if (verificationInfo != null) {
12930                        if (verificationInfo.originatingUri != null) {
12931                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12932                                    verificationInfo.originatingUri);
12933                        }
12934                        if (verificationInfo.referrer != null) {
12935                            verification.putExtra(Intent.EXTRA_REFERRER,
12936                                    verificationInfo.referrer);
12937                        }
12938                        if (verificationInfo.originatingUid >= 0) {
12939                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12940                                    verificationInfo.originatingUid);
12941                        }
12942                        if (verificationInfo.installerUid >= 0) {
12943                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12944                                    verificationInfo.installerUid);
12945                        }
12946                    }
12947
12948                    final PackageVerificationState verificationState = new PackageVerificationState(
12949                            requiredUid, args);
12950
12951                    mPendingVerification.append(verificationId, verificationState);
12952
12953                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12954                            receivers, verificationState);
12955
12956                    /*
12957                     * If any sufficient verifiers were listed in the package
12958                     * manifest, attempt to ask them.
12959                     */
12960                    if (sufficientVerifiers != null) {
12961                        final int N = sufficientVerifiers.size();
12962                        if (N == 0) {
12963                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12964                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12965                        } else {
12966                            for (int i = 0; i < N; i++) {
12967                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12968
12969                                final Intent sufficientIntent = new Intent(verification);
12970                                sufficientIntent.setComponent(verifierComponent);
12971                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12972                            }
12973                        }
12974                    }
12975
12976                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12977                            mRequiredVerifierPackage, receivers);
12978                    if (ret == PackageManager.INSTALL_SUCCEEDED
12979                            && mRequiredVerifierPackage != null) {
12980                        Trace.asyncTraceBegin(
12981                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12982                        /*
12983                         * Send the intent to the required verification agent,
12984                         * but only start the verification timeout after the
12985                         * target BroadcastReceivers have run.
12986                         */
12987                        verification.setComponent(requiredVerifierComponent);
12988                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12989                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12990                                new BroadcastReceiver() {
12991                                    @Override
12992                                    public void onReceive(Context context, Intent intent) {
12993                                        final Message msg = mHandler
12994                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12995                                        msg.arg1 = verificationId;
12996                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12997                                    }
12998                                }, null, 0, null, null);
12999
13000                        /*
13001                         * We don't want the copy to proceed until verification
13002                         * succeeds, so null out this field.
13003                         */
13004                        mArgs = null;
13005                    }
13006                } else {
13007                    /*
13008                     * No package verification is enabled, so immediately start
13009                     * the remote call to initiate copy using temporary file.
13010                     */
13011                    ret = args.copyApk(mContainerService, true);
13012                }
13013            }
13014
13015            mRet = ret;
13016        }
13017
13018        @Override
13019        void handleReturnCode() {
13020            // If mArgs is null, then MCS couldn't be reached. When it
13021            // reconnects, it will try again to install. At that point, this
13022            // will succeed.
13023            if (mArgs != null) {
13024                processPendingInstall(mArgs, mRet);
13025            }
13026        }
13027
13028        @Override
13029        void handleServiceError() {
13030            mArgs = createInstallArgs(this);
13031            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13032        }
13033
13034        public boolean isForwardLocked() {
13035            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13036        }
13037    }
13038
13039    /**
13040     * Used during creation of InstallArgs
13041     *
13042     * @param installFlags package installation flags
13043     * @return true if should be installed on external storage
13044     */
13045    private static boolean installOnExternalAsec(int installFlags) {
13046        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13047            return false;
13048        }
13049        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13050            return true;
13051        }
13052        return false;
13053    }
13054
13055    /**
13056     * Used during creation of InstallArgs
13057     *
13058     * @param installFlags package installation flags
13059     * @return true if should be installed as forward locked
13060     */
13061    private static boolean installForwardLocked(int installFlags) {
13062        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13063    }
13064
13065    private InstallArgs createInstallArgs(InstallParams params) {
13066        if (params.move != null) {
13067            return new MoveInstallArgs(params);
13068        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13069            return new AsecInstallArgs(params);
13070        } else {
13071            return new FileInstallArgs(params);
13072        }
13073    }
13074
13075    /**
13076     * Create args that describe an existing installed package. Typically used
13077     * when cleaning up old installs, or used as a move source.
13078     */
13079    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13080            String resourcePath, String[] instructionSets) {
13081        final boolean isInAsec;
13082        if (installOnExternalAsec(installFlags)) {
13083            /* Apps on SD card are always in ASEC containers. */
13084            isInAsec = true;
13085        } else if (installForwardLocked(installFlags)
13086                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13087            /*
13088             * Forward-locked apps are only in ASEC containers if they're the
13089             * new style
13090             */
13091            isInAsec = true;
13092        } else {
13093            isInAsec = false;
13094        }
13095
13096        if (isInAsec) {
13097            return new AsecInstallArgs(codePath, instructionSets,
13098                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13099        } else {
13100            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13101        }
13102    }
13103
13104    static abstract class InstallArgs {
13105        /** @see InstallParams#origin */
13106        final OriginInfo origin;
13107        /** @see InstallParams#move */
13108        final MoveInfo move;
13109
13110        final IPackageInstallObserver2 observer;
13111        // Always refers to PackageManager flags only
13112        final int installFlags;
13113        final String installerPackageName;
13114        final String volumeUuid;
13115        final UserHandle user;
13116        final String abiOverride;
13117        final String[] installGrantPermissions;
13118        /** If non-null, drop an async trace when the install completes */
13119        final String traceMethod;
13120        final int traceCookie;
13121        final Certificate[][] certificates;
13122
13123        // The list of instruction sets supported by this app. This is currently
13124        // only used during the rmdex() phase to clean up resources. We can get rid of this
13125        // if we move dex files under the common app path.
13126        /* nullable */ String[] instructionSets;
13127
13128        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13129                int installFlags, String installerPackageName, String volumeUuid,
13130                UserHandle user, String[] instructionSets,
13131                String abiOverride, String[] installGrantPermissions,
13132                String traceMethod, int traceCookie, Certificate[][] certificates) {
13133            this.origin = origin;
13134            this.move = move;
13135            this.installFlags = installFlags;
13136            this.observer = observer;
13137            this.installerPackageName = installerPackageName;
13138            this.volumeUuid = volumeUuid;
13139            this.user = user;
13140            this.instructionSets = instructionSets;
13141            this.abiOverride = abiOverride;
13142            this.installGrantPermissions = installGrantPermissions;
13143            this.traceMethod = traceMethod;
13144            this.traceCookie = traceCookie;
13145            this.certificates = certificates;
13146        }
13147
13148        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13149        abstract int doPreInstall(int status);
13150
13151        /**
13152         * Rename package into final resting place. All paths on the given
13153         * scanned package should be updated to reflect the rename.
13154         */
13155        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13156        abstract int doPostInstall(int status, int uid);
13157
13158        /** @see PackageSettingBase#codePathString */
13159        abstract String getCodePath();
13160        /** @see PackageSettingBase#resourcePathString */
13161        abstract String getResourcePath();
13162
13163        // Need installer lock especially for dex file removal.
13164        abstract void cleanUpResourcesLI();
13165        abstract boolean doPostDeleteLI(boolean delete);
13166
13167        /**
13168         * Called before the source arguments are copied. This is used mostly
13169         * for MoveParams when it needs to read the source file to put it in the
13170         * destination.
13171         */
13172        int doPreCopy() {
13173            return PackageManager.INSTALL_SUCCEEDED;
13174        }
13175
13176        /**
13177         * Called after the source arguments are copied. This is used mostly for
13178         * MoveParams when it needs to read the source file to put it in the
13179         * destination.
13180         */
13181        int doPostCopy(int uid) {
13182            return PackageManager.INSTALL_SUCCEEDED;
13183        }
13184
13185        protected boolean isFwdLocked() {
13186            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13187        }
13188
13189        protected boolean isExternalAsec() {
13190            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13191        }
13192
13193        protected boolean isEphemeral() {
13194            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13195        }
13196
13197        UserHandle getUser() {
13198            return user;
13199        }
13200    }
13201
13202    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13203        if (!allCodePaths.isEmpty()) {
13204            if (instructionSets == null) {
13205                throw new IllegalStateException("instructionSet == null");
13206            }
13207            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13208            for (String codePath : allCodePaths) {
13209                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13210                    try {
13211                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13212                    } catch (InstallerException ignored) {
13213                    }
13214                }
13215            }
13216        }
13217    }
13218
13219    /**
13220     * Logic to handle installation of non-ASEC applications, including copying
13221     * and renaming logic.
13222     */
13223    class FileInstallArgs extends InstallArgs {
13224        private File codeFile;
13225        private File resourceFile;
13226
13227        // Example topology:
13228        // /data/app/com.example/base.apk
13229        // /data/app/com.example/split_foo.apk
13230        // /data/app/com.example/lib/arm/libfoo.so
13231        // /data/app/com.example/lib/arm64/libfoo.so
13232        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13233
13234        /** New install */
13235        FileInstallArgs(InstallParams params) {
13236            super(params.origin, params.move, params.observer, params.installFlags,
13237                    params.installerPackageName, params.volumeUuid,
13238                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13239                    params.grantedRuntimePermissions,
13240                    params.traceMethod, params.traceCookie, params.certificates);
13241            if (isFwdLocked()) {
13242                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13243            }
13244        }
13245
13246        /** Existing install */
13247        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13248            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13249                    null, null, null, 0, null /*certificates*/);
13250            this.codeFile = (codePath != null) ? new File(codePath) : null;
13251            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13252        }
13253
13254        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13255            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13256            try {
13257                return doCopyApk(imcs, temp);
13258            } finally {
13259                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13260            }
13261        }
13262
13263        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13264            if (origin.staged) {
13265                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13266                codeFile = origin.file;
13267                resourceFile = origin.file;
13268                return PackageManager.INSTALL_SUCCEEDED;
13269            }
13270
13271            try {
13272                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13273                final File tempDir =
13274                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13275                codeFile = tempDir;
13276                resourceFile = tempDir;
13277            } catch (IOException e) {
13278                Slog.w(TAG, "Failed to create copy file: " + e);
13279                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13280            }
13281
13282            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13283                @Override
13284                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13285                    if (!FileUtils.isValidExtFilename(name)) {
13286                        throw new IllegalArgumentException("Invalid filename: " + name);
13287                    }
13288                    try {
13289                        final File file = new File(codeFile, name);
13290                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13291                                O_RDWR | O_CREAT, 0644);
13292                        Os.chmod(file.getAbsolutePath(), 0644);
13293                        return new ParcelFileDescriptor(fd);
13294                    } catch (ErrnoException e) {
13295                        throw new RemoteException("Failed to open: " + e.getMessage());
13296                    }
13297                }
13298            };
13299
13300            int ret = PackageManager.INSTALL_SUCCEEDED;
13301            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13302            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13303                Slog.e(TAG, "Failed to copy package");
13304                return ret;
13305            }
13306
13307            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13308            NativeLibraryHelper.Handle handle = null;
13309            try {
13310                handle = NativeLibraryHelper.Handle.create(codeFile);
13311                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13312                        abiOverride);
13313            } catch (IOException e) {
13314                Slog.e(TAG, "Copying native libraries failed", e);
13315                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13316            } finally {
13317                IoUtils.closeQuietly(handle);
13318            }
13319
13320            return ret;
13321        }
13322
13323        int doPreInstall(int status) {
13324            if (status != PackageManager.INSTALL_SUCCEEDED) {
13325                cleanUp();
13326            }
13327            return status;
13328        }
13329
13330        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13331            if (status != PackageManager.INSTALL_SUCCEEDED) {
13332                cleanUp();
13333                return false;
13334            }
13335
13336            final File targetDir = codeFile.getParentFile();
13337            final File beforeCodeFile = codeFile;
13338            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13339
13340            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13341            try {
13342                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13343            } catch (ErrnoException e) {
13344                Slog.w(TAG, "Failed to rename", e);
13345                return false;
13346            }
13347
13348            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13349                Slog.w(TAG, "Failed to restorecon");
13350                return false;
13351            }
13352
13353            // Reflect the rename internally
13354            codeFile = afterCodeFile;
13355            resourceFile = afterCodeFile;
13356
13357            // Reflect the rename in scanned details
13358            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13359            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13360                    afterCodeFile, pkg.baseCodePath));
13361            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13362                    afterCodeFile, pkg.splitCodePaths));
13363
13364            // Reflect the rename in app info
13365            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13366            pkg.setApplicationInfoCodePath(pkg.codePath);
13367            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13368            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13369            pkg.setApplicationInfoResourcePath(pkg.codePath);
13370            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13371            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13372
13373            return true;
13374        }
13375
13376        int doPostInstall(int status, int uid) {
13377            if (status != PackageManager.INSTALL_SUCCEEDED) {
13378                cleanUp();
13379            }
13380            return status;
13381        }
13382
13383        @Override
13384        String getCodePath() {
13385            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13386        }
13387
13388        @Override
13389        String getResourcePath() {
13390            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13391        }
13392
13393        private boolean cleanUp() {
13394            if (codeFile == null || !codeFile.exists()) {
13395                return false;
13396            }
13397
13398            removeCodePathLI(codeFile);
13399
13400            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13401                resourceFile.delete();
13402            }
13403
13404            return true;
13405        }
13406
13407        void cleanUpResourcesLI() {
13408            // Try enumerating all code paths before deleting
13409            List<String> allCodePaths = Collections.EMPTY_LIST;
13410            if (codeFile != null && codeFile.exists()) {
13411                try {
13412                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13413                    allCodePaths = pkg.getAllCodePaths();
13414                } catch (PackageParserException e) {
13415                    // Ignored; we tried our best
13416                }
13417            }
13418
13419            cleanUp();
13420            removeDexFiles(allCodePaths, instructionSets);
13421        }
13422
13423        boolean doPostDeleteLI(boolean delete) {
13424            // XXX err, shouldn't we respect the delete flag?
13425            cleanUpResourcesLI();
13426            return true;
13427        }
13428    }
13429
13430    private boolean isAsecExternal(String cid) {
13431        final String asecPath = PackageHelper.getSdFilesystem(cid);
13432        return !asecPath.startsWith(mAsecInternalPath);
13433    }
13434
13435    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13436            PackageManagerException {
13437        if (copyRet < 0) {
13438            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13439                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13440                throw new PackageManagerException(copyRet, message);
13441            }
13442        }
13443    }
13444
13445    /**
13446     * Extract the MountService "container ID" from the full code path of an
13447     * .apk.
13448     */
13449    static String cidFromCodePath(String fullCodePath) {
13450        int eidx = fullCodePath.lastIndexOf("/");
13451        String subStr1 = fullCodePath.substring(0, eidx);
13452        int sidx = subStr1.lastIndexOf("/");
13453        return subStr1.substring(sidx+1, eidx);
13454    }
13455
13456    /**
13457     * Logic to handle installation of ASEC applications, including copying and
13458     * renaming logic.
13459     */
13460    class AsecInstallArgs extends InstallArgs {
13461        static final String RES_FILE_NAME = "pkg.apk";
13462        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13463
13464        String cid;
13465        String packagePath;
13466        String resourcePath;
13467
13468        /** New install */
13469        AsecInstallArgs(InstallParams params) {
13470            super(params.origin, params.move, params.observer, params.installFlags,
13471                    params.installerPackageName, params.volumeUuid,
13472                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13473                    params.grantedRuntimePermissions,
13474                    params.traceMethod, params.traceCookie, params.certificates);
13475        }
13476
13477        /** Existing install */
13478        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13479                        boolean isExternal, boolean isForwardLocked) {
13480            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13481              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13482                    instructionSets, null, null, null, 0, null /*certificates*/);
13483            // Hackily pretend we're still looking at a full code path
13484            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13485                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13486            }
13487
13488            // Extract cid from fullCodePath
13489            int eidx = fullCodePath.lastIndexOf("/");
13490            String subStr1 = fullCodePath.substring(0, eidx);
13491            int sidx = subStr1.lastIndexOf("/");
13492            cid = subStr1.substring(sidx+1, eidx);
13493            setMountPath(subStr1);
13494        }
13495
13496        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13497            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13498              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13499                    instructionSets, null, null, null, 0, null /*certificates*/);
13500            this.cid = cid;
13501            setMountPath(PackageHelper.getSdDir(cid));
13502        }
13503
13504        void createCopyFile() {
13505            cid = mInstallerService.allocateExternalStageCidLegacy();
13506        }
13507
13508        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13509            if (origin.staged && origin.cid != null) {
13510                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13511                cid = origin.cid;
13512                setMountPath(PackageHelper.getSdDir(cid));
13513                return PackageManager.INSTALL_SUCCEEDED;
13514            }
13515
13516            if (temp) {
13517                createCopyFile();
13518            } else {
13519                /*
13520                 * Pre-emptively destroy the container since it's destroyed if
13521                 * copying fails due to it existing anyway.
13522                 */
13523                PackageHelper.destroySdDir(cid);
13524            }
13525
13526            final String newMountPath = imcs.copyPackageToContainer(
13527                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13528                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13529
13530            if (newMountPath != null) {
13531                setMountPath(newMountPath);
13532                return PackageManager.INSTALL_SUCCEEDED;
13533            } else {
13534                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13535            }
13536        }
13537
13538        @Override
13539        String getCodePath() {
13540            return packagePath;
13541        }
13542
13543        @Override
13544        String getResourcePath() {
13545            return resourcePath;
13546        }
13547
13548        int doPreInstall(int status) {
13549            if (status != PackageManager.INSTALL_SUCCEEDED) {
13550                // Destroy container
13551                PackageHelper.destroySdDir(cid);
13552            } else {
13553                boolean mounted = PackageHelper.isContainerMounted(cid);
13554                if (!mounted) {
13555                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13556                            Process.SYSTEM_UID);
13557                    if (newMountPath != null) {
13558                        setMountPath(newMountPath);
13559                    } else {
13560                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13561                    }
13562                }
13563            }
13564            return status;
13565        }
13566
13567        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13568            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13569            String newMountPath = null;
13570            if (PackageHelper.isContainerMounted(cid)) {
13571                // Unmount the container
13572                if (!PackageHelper.unMountSdDir(cid)) {
13573                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13574                    return false;
13575                }
13576            }
13577            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13578                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13579                        " which might be stale. Will try to clean up.");
13580                // Clean up the stale container and proceed to recreate.
13581                if (!PackageHelper.destroySdDir(newCacheId)) {
13582                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13583                    return false;
13584                }
13585                // Successfully cleaned up stale container. Try to rename again.
13586                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13587                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13588                            + " inspite of cleaning it up.");
13589                    return false;
13590                }
13591            }
13592            if (!PackageHelper.isContainerMounted(newCacheId)) {
13593                Slog.w(TAG, "Mounting container " + newCacheId);
13594                newMountPath = PackageHelper.mountSdDir(newCacheId,
13595                        getEncryptKey(), Process.SYSTEM_UID);
13596            } else {
13597                newMountPath = PackageHelper.getSdDir(newCacheId);
13598            }
13599            if (newMountPath == null) {
13600                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13601                return false;
13602            }
13603            Log.i(TAG, "Succesfully renamed " + cid +
13604                    " to " + newCacheId +
13605                    " at new path: " + newMountPath);
13606            cid = newCacheId;
13607
13608            final File beforeCodeFile = new File(packagePath);
13609            setMountPath(newMountPath);
13610            final File afterCodeFile = new File(packagePath);
13611
13612            // Reflect the rename in scanned details
13613            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13614            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13615                    afterCodeFile, pkg.baseCodePath));
13616            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13617                    afterCodeFile, pkg.splitCodePaths));
13618
13619            // Reflect the rename in app info
13620            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13621            pkg.setApplicationInfoCodePath(pkg.codePath);
13622            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13623            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13624            pkg.setApplicationInfoResourcePath(pkg.codePath);
13625            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13626            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13627
13628            return true;
13629        }
13630
13631        private void setMountPath(String mountPath) {
13632            final File mountFile = new File(mountPath);
13633
13634            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13635            if (monolithicFile.exists()) {
13636                packagePath = monolithicFile.getAbsolutePath();
13637                if (isFwdLocked()) {
13638                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13639                } else {
13640                    resourcePath = packagePath;
13641                }
13642            } else {
13643                packagePath = mountFile.getAbsolutePath();
13644                resourcePath = packagePath;
13645            }
13646        }
13647
13648        int doPostInstall(int status, int uid) {
13649            if (status != PackageManager.INSTALL_SUCCEEDED) {
13650                cleanUp();
13651            } else {
13652                final int groupOwner;
13653                final String protectedFile;
13654                if (isFwdLocked()) {
13655                    groupOwner = UserHandle.getSharedAppGid(uid);
13656                    protectedFile = RES_FILE_NAME;
13657                } else {
13658                    groupOwner = -1;
13659                    protectedFile = null;
13660                }
13661
13662                if (uid < Process.FIRST_APPLICATION_UID
13663                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13664                    Slog.e(TAG, "Failed to finalize " + cid);
13665                    PackageHelper.destroySdDir(cid);
13666                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13667                }
13668
13669                boolean mounted = PackageHelper.isContainerMounted(cid);
13670                if (!mounted) {
13671                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13672                }
13673            }
13674            return status;
13675        }
13676
13677        private void cleanUp() {
13678            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13679
13680            // Destroy secure container
13681            PackageHelper.destroySdDir(cid);
13682        }
13683
13684        private List<String> getAllCodePaths() {
13685            final File codeFile = new File(getCodePath());
13686            if (codeFile != null && codeFile.exists()) {
13687                try {
13688                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13689                    return pkg.getAllCodePaths();
13690                } catch (PackageParserException e) {
13691                    // Ignored; we tried our best
13692                }
13693            }
13694            return Collections.EMPTY_LIST;
13695        }
13696
13697        void cleanUpResourcesLI() {
13698            // Enumerate all code paths before deleting
13699            cleanUpResourcesLI(getAllCodePaths());
13700        }
13701
13702        private void cleanUpResourcesLI(List<String> allCodePaths) {
13703            cleanUp();
13704            removeDexFiles(allCodePaths, instructionSets);
13705        }
13706
13707        String getPackageName() {
13708            return getAsecPackageName(cid);
13709        }
13710
13711        boolean doPostDeleteLI(boolean delete) {
13712            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13713            final List<String> allCodePaths = getAllCodePaths();
13714            boolean mounted = PackageHelper.isContainerMounted(cid);
13715            if (mounted) {
13716                // Unmount first
13717                if (PackageHelper.unMountSdDir(cid)) {
13718                    mounted = false;
13719                }
13720            }
13721            if (!mounted && delete) {
13722                cleanUpResourcesLI(allCodePaths);
13723            }
13724            return !mounted;
13725        }
13726
13727        @Override
13728        int doPreCopy() {
13729            if (isFwdLocked()) {
13730                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13731                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13732                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13733                }
13734            }
13735
13736            return PackageManager.INSTALL_SUCCEEDED;
13737        }
13738
13739        @Override
13740        int doPostCopy(int uid) {
13741            if (isFwdLocked()) {
13742                if (uid < Process.FIRST_APPLICATION_UID
13743                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13744                                RES_FILE_NAME)) {
13745                    Slog.e(TAG, "Failed to finalize " + cid);
13746                    PackageHelper.destroySdDir(cid);
13747                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13748                }
13749            }
13750
13751            return PackageManager.INSTALL_SUCCEEDED;
13752        }
13753    }
13754
13755    /**
13756     * Logic to handle movement of existing installed applications.
13757     */
13758    class MoveInstallArgs extends InstallArgs {
13759        private File codeFile;
13760        private File resourceFile;
13761
13762        /** New install */
13763        MoveInstallArgs(InstallParams params) {
13764            super(params.origin, params.move, params.observer, params.installFlags,
13765                    params.installerPackageName, params.volumeUuid,
13766                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13767                    params.grantedRuntimePermissions,
13768                    params.traceMethod, params.traceCookie, params.certificates);
13769        }
13770
13771        int copyApk(IMediaContainerService imcs, boolean temp) {
13772            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13773                    + move.fromUuid + " to " + move.toUuid);
13774            synchronized (mInstaller) {
13775                try {
13776                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13777                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13778                } catch (InstallerException e) {
13779                    Slog.w(TAG, "Failed to move app", e);
13780                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13781                }
13782            }
13783
13784            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13785            resourceFile = codeFile;
13786            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13787
13788            return PackageManager.INSTALL_SUCCEEDED;
13789        }
13790
13791        int doPreInstall(int status) {
13792            if (status != PackageManager.INSTALL_SUCCEEDED) {
13793                cleanUp(move.toUuid);
13794            }
13795            return status;
13796        }
13797
13798        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13799            if (status != PackageManager.INSTALL_SUCCEEDED) {
13800                cleanUp(move.toUuid);
13801                return false;
13802            }
13803
13804            // Reflect the move in app info
13805            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13806            pkg.setApplicationInfoCodePath(pkg.codePath);
13807            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13808            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13809            pkg.setApplicationInfoResourcePath(pkg.codePath);
13810            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13811            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13812
13813            return true;
13814        }
13815
13816        int doPostInstall(int status, int uid) {
13817            if (status == PackageManager.INSTALL_SUCCEEDED) {
13818                cleanUp(move.fromUuid);
13819            } else {
13820                cleanUp(move.toUuid);
13821            }
13822            return status;
13823        }
13824
13825        @Override
13826        String getCodePath() {
13827            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13828        }
13829
13830        @Override
13831        String getResourcePath() {
13832            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13833        }
13834
13835        private boolean cleanUp(String volumeUuid) {
13836            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13837                    move.dataAppName);
13838            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13839            final int[] userIds = sUserManager.getUserIds();
13840            synchronized (mInstallLock) {
13841                // Clean up both app data and code
13842                // All package moves are frozen until finished
13843                for (int userId : userIds) {
13844                    try {
13845                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13846                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13847                    } catch (InstallerException e) {
13848                        Slog.w(TAG, String.valueOf(e));
13849                    }
13850                }
13851                removeCodePathLI(codeFile);
13852            }
13853            return true;
13854        }
13855
13856        void cleanUpResourcesLI() {
13857            throw new UnsupportedOperationException();
13858        }
13859
13860        boolean doPostDeleteLI(boolean delete) {
13861            throw new UnsupportedOperationException();
13862        }
13863    }
13864
13865    static String getAsecPackageName(String packageCid) {
13866        int idx = packageCid.lastIndexOf("-");
13867        if (idx == -1) {
13868            return packageCid;
13869        }
13870        return packageCid.substring(0, idx);
13871    }
13872
13873    // Utility method used to create code paths based on package name and available index.
13874    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13875        String idxStr = "";
13876        int idx = 1;
13877        // Fall back to default value of idx=1 if prefix is not
13878        // part of oldCodePath
13879        if (oldCodePath != null) {
13880            String subStr = oldCodePath;
13881            // Drop the suffix right away
13882            if (suffix != null && subStr.endsWith(suffix)) {
13883                subStr = subStr.substring(0, subStr.length() - suffix.length());
13884            }
13885            // If oldCodePath already contains prefix find out the
13886            // ending index to either increment or decrement.
13887            int sidx = subStr.lastIndexOf(prefix);
13888            if (sidx != -1) {
13889                subStr = subStr.substring(sidx + prefix.length());
13890                if (subStr != null) {
13891                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13892                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13893                    }
13894                    try {
13895                        idx = Integer.parseInt(subStr);
13896                        if (idx <= 1) {
13897                            idx++;
13898                        } else {
13899                            idx--;
13900                        }
13901                    } catch(NumberFormatException e) {
13902                    }
13903                }
13904            }
13905        }
13906        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13907        return prefix + idxStr;
13908    }
13909
13910    private File getNextCodePath(File targetDir, String packageName) {
13911        int suffix = 1;
13912        File result;
13913        do {
13914            result = new File(targetDir, packageName + "-" + suffix);
13915            suffix++;
13916        } while (result.exists());
13917        return result;
13918    }
13919
13920    // Utility method that returns the relative package path with respect
13921    // to the installation directory. Like say for /data/data/com.test-1.apk
13922    // string com.test-1 is returned.
13923    static String deriveCodePathName(String codePath) {
13924        if (codePath == null) {
13925            return null;
13926        }
13927        final File codeFile = new File(codePath);
13928        final String name = codeFile.getName();
13929        if (codeFile.isDirectory()) {
13930            return name;
13931        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13932            final int lastDot = name.lastIndexOf('.');
13933            return name.substring(0, lastDot);
13934        } else {
13935            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13936            return null;
13937        }
13938    }
13939
13940    static class PackageInstalledInfo {
13941        String name;
13942        int uid;
13943        // The set of users that originally had this package installed.
13944        int[] origUsers;
13945        // The set of users that now have this package installed.
13946        int[] newUsers;
13947        PackageParser.Package pkg;
13948        int returnCode;
13949        String returnMsg;
13950        PackageRemovedInfo removedInfo;
13951        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13952
13953        public void setError(int code, String msg) {
13954            setReturnCode(code);
13955            setReturnMessage(msg);
13956            Slog.w(TAG, msg);
13957        }
13958
13959        public void setError(String msg, PackageParserException e) {
13960            setReturnCode(e.error);
13961            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13962            Slog.w(TAG, msg, e);
13963        }
13964
13965        public void setError(String msg, PackageManagerException e) {
13966            returnCode = e.error;
13967            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13968            Slog.w(TAG, msg, e);
13969        }
13970
13971        public void setReturnCode(int returnCode) {
13972            this.returnCode = returnCode;
13973            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13974            for (int i = 0; i < childCount; i++) {
13975                addedChildPackages.valueAt(i).returnCode = returnCode;
13976            }
13977        }
13978
13979        private void setReturnMessage(String returnMsg) {
13980            this.returnMsg = returnMsg;
13981            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13982            for (int i = 0; i < childCount; i++) {
13983                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13984            }
13985        }
13986
13987        // In some error cases we want to convey more info back to the observer
13988        String origPackage;
13989        String origPermission;
13990    }
13991
13992    /*
13993     * Install a non-existing package.
13994     */
13995    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
13996            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
13997            PackageInstalledInfo res) {
13998        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13999
14000        // Remember this for later, in case we need to rollback this install
14001        String pkgName = pkg.packageName;
14002
14003        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14004
14005        synchronized(mPackages) {
14006            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14007                // A package with the same name is already installed, though
14008                // it has been renamed to an older name.  The package we
14009                // are trying to install should be installed as an update to
14010                // the existing one, but that has not been requested, so bail.
14011                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14012                        + " without first uninstalling package running as "
14013                        + mSettings.mRenamedPackages.get(pkgName));
14014                return;
14015            }
14016            if (mPackages.containsKey(pkgName)) {
14017                // Don't allow installation over an existing package with the same name.
14018                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14019                        + " without first uninstalling.");
14020                return;
14021            }
14022        }
14023
14024        try {
14025            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14026                    System.currentTimeMillis(), user);
14027
14028            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14029
14030            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14031                prepareAppDataAfterInstallLIF(newPackage);
14032
14033            } else {
14034                // Remove package from internal structures, but keep around any
14035                // data that might have already existed
14036                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14037                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14038            }
14039        } catch (PackageManagerException e) {
14040            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14041        }
14042
14043        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14044    }
14045
14046    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14047        // Can't rotate keys during boot or if sharedUser.
14048        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14049                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14050            return false;
14051        }
14052        // app is using upgradeKeySets; make sure all are valid
14053        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14054        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14055        for (int i = 0; i < upgradeKeySets.length; i++) {
14056            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14057                Slog.wtf(TAG, "Package "
14058                         + (oldPs.name != null ? oldPs.name : "<null>")
14059                         + " contains upgrade-key-set reference to unknown key-set: "
14060                         + upgradeKeySets[i]
14061                         + " reverting to signatures check.");
14062                return false;
14063            }
14064        }
14065        return true;
14066    }
14067
14068    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14069        // Upgrade keysets are being used.  Determine if new package has a superset of the
14070        // required keys.
14071        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14072        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14073        for (int i = 0; i < upgradeKeySets.length; i++) {
14074            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14075            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14076                return true;
14077            }
14078        }
14079        return false;
14080    }
14081
14082    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14083        try (DigestInputStream digestStream =
14084                new DigestInputStream(new FileInputStream(file), digest)) {
14085            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14086        }
14087    }
14088
14089    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14090            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14091        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14092
14093        final PackageParser.Package oldPackage;
14094        final String pkgName = pkg.packageName;
14095        final int[] allUsers;
14096        final int[] installedUsers;
14097
14098        synchronized(mPackages) {
14099            oldPackage = mPackages.get(pkgName);
14100            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14101
14102            // don't allow upgrade to target a release SDK from a pre-release SDK
14103            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14104                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14105            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14106                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14107            if (oldTargetsPreRelease
14108                    && !newTargetsPreRelease
14109                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14110                Slog.w(TAG, "Can't install package targeting released sdk");
14111                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14112                return;
14113            }
14114
14115            // don't allow an upgrade from full to ephemeral
14116            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14117            if (isEphemeral && !oldIsEphemeral) {
14118                // can't downgrade from full to ephemeral
14119                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14120                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14121                return;
14122            }
14123
14124            // verify signatures are valid
14125            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14126            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14127                if (!checkUpgradeKeySetLP(ps, pkg)) {
14128                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14129                            "New package not signed by keys specified by upgrade-keysets: "
14130                                    + pkgName);
14131                    return;
14132                }
14133            } else {
14134                // default to original signature matching
14135                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14136                        != PackageManager.SIGNATURE_MATCH) {
14137                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14138                            "New package has a different signature: " + pkgName);
14139                    return;
14140                }
14141            }
14142
14143            // don't allow a system upgrade unless the upgrade hash matches
14144            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14145                byte[] digestBytes = null;
14146                try {
14147                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14148                    updateDigest(digest, new File(pkg.baseCodePath));
14149                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14150                        for (String path : pkg.splitCodePaths) {
14151                            updateDigest(digest, new File(path));
14152                        }
14153                    }
14154                    digestBytes = digest.digest();
14155                } catch (NoSuchAlgorithmException | IOException e) {
14156                    res.setError(INSTALL_FAILED_INVALID_APK,
14157                            "Could not compute hash: " + pkgName);
14158                    return;
14159                }
14160                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14161                    res.setError(INSTALL_FAILED_INVALID_APK,
14162                            "New package fails restrict-update check: " + pkgName);
14163                    return;
14164                }
14165                // retain upgrade restriction
14166                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14167            }
14168
14169            // Check for shared user id changes
14170            String invalidPackageName =
14171                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14172            if (invalidPackageName != null) {
14173                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14174                        "Package " + invalidPackageName + " tried to change user "
14175                                + oldPackage.mSharedUserId);
14176                return;
14177            }
14178
14179            // In case of rollback, remember per-user/profile install state
14180            allUsers = sUserManager.getUserIds();
14181            installedUsers = ps.queryInstalledUsers(allUsers, true);
14182        }
14183
14184        // Update what is removed
14185        res.removedInfo = new PackageRemovedInfo();
14186        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14187        res.removedInfo.removedPackage = oldPackage.packageName;
14188        res.removedInfo.isUpdate = true;
14189        res.removedInfo.origUsers = installedUsers;
14190        final int childCount = (oldPackage.childPackages != null)
14191                ? oldPackage.childPackages.size() : 0;
14192        for (int i = 0; i < childCount; i++) {
14193            boolean childPackageUpdated = false;
14194            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14195            if (res.addedChildPackages != null) {
14196                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14197                if (childRes != null) {
14198                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14199                    childRes.removedInfo.removedPackage = childPkg.packageName;
14200                    childRes.removedInfo.isUpdate = true;
14201                    childPackageUpdated = true;
14202                }
14203            }
14204            if (!childPackageUpdated) {
14205                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14206                childRemovedRes.removedPackage = childPkg.packageName;
14207                childRemovedRes.isUpdate = false;
14208                childRemovedRes.dataRemoved = true;
14209                synchronized (mPackages) {
14210                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14211                    if (childPs != null) {
14212                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14213                    }
14214                }
14215                if (res.removedInfo.removedChildPackages == null) {
14216                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14217                }
14218                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14219            }
14220        }
14221
14222        boolean sysPkg = (isSystemApp(oldPackage));
14223        if (sysPkg) {
14224            // Set the system/privileged flags as needed
14225            final boolean privileged =
14226                    (oldPackage.applicationInfo.privateFlags
14227                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14228            final int systemPolicyFlags = policyFlags
14229                    | PackageParser.PARSE_IS_SYSTEM
14230                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14231
14232            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14233                    user, allUsers, installerPackageName, res);
14234        } else {
14235            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14236                    user, allUsers, installerPackageName, res);
14237        }
14238    }
14239
14240    public List<String> getPreviousCodePaths(String packageName) {
14241        final PackageSetting ps = mSettings.mPackages.get(packageName);
14242        final List<String> result = new ArrayList<String>();
14243        if (ps != null && ps.oldCodePaths != null) {
14244            result.addAll(ps.oldCodePaths);
14245        }
14246        return result;
14247    }
14248
14249    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14250            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14251            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14252        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14253                + deletedPackage);
14254
14255        String pkgName = deletedPackage.packageName;
14256        boolean deletedPkg = true;
14257        boolean addedPkg = false;
14258        boolean updatedSettings = false;
14259        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14260        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14261                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14262
14263        final long origUpdateTime = (pkg.mExtras != null)
14264                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14265
14266        // First delete the existing package while retaining the data directory
14267        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14268                res.removedInfo, true, pkg)) {
14269            // If the existing package wasn't successfully deleted
14270            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14271            deletedPkg = false;
14272        } else {
14273            // Successfully deleted the old package; proceed with replace.
14274
14275            // If deleted package lived in a container, give users a chance to
14276            // relinquish resources before killing.
14277            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14278                if (DEBUG_INSTALL) {
14279                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14280                }
14281                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14282                final ArrayList<String> pkgList = new ArrayList<String>(1);
14283                pkgList.add(deletedPackage.applicationInfo.packageName);
14284                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14285            }
14286
14287            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14288                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14289            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14290
14291            try {
14292                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14293                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14294                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14295
14296                // Update the in-memory copy of the previous code paths.
14297                PackageSetting ps = mSettings.mPackages.get(pkgName);
14298                if (!killApp) {
14299                    if (ps.oldCodePaths == null) {
14300                        ps.oldCodePaths = new ArraySet<>();
14301                    }
14302                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14303                    if (deletedPackage.splitCodePaths != null) {
14304                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14305                    }
14306                } else {
14307                    ps.oldCodePaths = null;
14308                }
14309                if (ps.childPackageNames != null) {
14310                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14311                        final String childPkgName = ps.childPackageNames.get(i);
14312                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14313                        childPs.oldCodePaths = ps.oldCodePaths;
14314                    }
14315                }
14316                prepareAppDataAfterInstallLIF(newPackage);
14317                addedPkg = true;
14318            } catch (PackageManagerException e) {
14319                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14320            }
14321        }
14322
14323        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14324            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14325
14326            // Revert all internal state mutations and added folders for the failed install
14327            if (addedPkg) {
14328                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14329                        res.removedInfo, true, null);
14330            }
14331
14332            // Restore the old package
14333            if (deletedPkg) {
14334                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14335                File restoreFile = new File(deletedPackage.codePath);
14336                // Parse old package
14337                boolean oldExternal = isExternal(deletedPackage);
14338                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14339                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14340                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14341                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14342                try {
14343                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14344                            null);
14345                } catch (PackageManagerException e) {
14346                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14347                            + e.getMessage());
14348                    return;
14349                }
14350
14351                synchronized (mPackages) {
14352                    // Ensure the installer package name up to date
14353                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14354
14355                    // Update permissions for restored package
14356                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14357
14358                    mSettings.writeLPr();
14359                }
14360
14361                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14362            }
14363        } else {
14364            synchronized (mPackages) {
14365                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14366                if (ps != null) {
14367                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14368                    if (res.removedInfo.removedChildPackages != null) {
14369                        final int childCount = res.removedInfo.removedChildPackages.size();
14370                        // Iterate in reverse as we may modify the collection
14371                        for (int i = childCount - 1; i >= 0; i--) {
14372                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14373                            if (res.addedChildPackages.containsKey(childPackageName)) {
14374                                res.removedInfo.removedChildPackages.removeAt(i);
14375                            } else {
14376                                PackageRemovedInfo childInfo = res.removedInfo
14377                                        .removedChildPackages.valueAt(i);
14378                                childInfo.removedForAllUsers = mPackages.get(
14379                                        childInfo.removedPackage) == null;
14380                            }
14381                        }
14382                    }
14383                }
14384            }
14385        }
14386    }
14387
14388    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14389            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14390            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14391        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14392                + ", old=" + deletedPackage);
14393
14394        final boolean disabledSystem;
14395
14396        // Remove existing system package
14397        removePackageLI(deletedPackage, true);
14398
14399        synchronized (mPackages) {
14400            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14401        }
14402        if (!disabledSystem) {
14403            // We didn't need to disable the .apk as a current system package,
14404            // which means we are replacing another update that is already
14405            // installed.  We need to make sure to delete the older one's .apk.
14406            res.removedInfo.args = createInstallArgsForExisting(0,
14407                    deletedPackage.applicationInfo.getCodePath(),
14408                    deletedPackage.applicationInfo.getResourcePath(),
14409                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14410        } else {
14411            res.removedInfo.args = null;
14412        }
14413
14414        // Successfully disabled the old package. Now proceed with re-installation
14415        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14416                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14417        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14418
14419        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14420        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14421                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14422
14423        PackageParser.Package newPackage = null;
14424        try {
14425            // Add the package to the internal data structures
14426            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14427
14428            // Set the update and install times
14429            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14430            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14431                    System.currentTimeMillis());
14432
14433            // Update the package dynamic state if succeeded
14434            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14435                // Now that the install succeeded make sure we remove data
14436                // directories for any child package the update removed.
14437                final int deletedChildCount = (deletedPackage.childPackages != null)
14438                        ? deletedPackage.childPackages.size() : 0;
14439                final int newChildCount = (newPackage.childPackages != null)
14440                        ? newPackage.childPackages.size() : 0;
14441                for (int i = 0; i < deletedChildCount; i++) {
14442                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14443                    boolean childPackageDeleted = true;
14444                    for (int j = 0; j < newChildCount; j++) {
14445                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14446                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14447                            childPackageDeleted = false;
14448                            break;
14449                        }
14450                    }
14451                    if (childPackageDeleted) {
14452                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14453                                deletedChildPkg.packageName);
14454                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14455                            PackageRemovedInfo removedChildRes = res.removedInfo
14456                                    .removedChildPackages.get(deletedChildPkg.packageName);
14457                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14458                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14459                        }
14460                    }
14461                }
14462
14463                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14464                prepareAppDataAfterInstallLIF(newPackage);
14465            }
14466        } catch (PackageManagerException e) {
14467            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14468            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14469        }
14470
14471        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14472            // Re installation failed. Restore old information
14473            // Remove new pkg information
14474            if (newPackage != null) {
14475                removeInstalledPackageLI(newPackage, true);
14476            }
14477            // Add back the old system package
14478            try {
14479                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14480            } catch (PackageManagerException e) {
14481                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14482            }
14483
14484            synchronized (mPackages) {
14485                if (disabledSystem) {
14486                    enableSystemPackageLPw(deletedPackage);
14487                }
14488
14489                // Ensure the installer package name up to date
14490                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14491
14492                // Update permissions for restored package
14493                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14494
14495                mSettings.writeLPr();
14496            }
14497
14498            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14499                    + " after failed upgrade");
14500        }
14501    }
14502
14503    /**
14504     * Checks whether the parent or any of the child packages have a change shared
14505     * user. For a package to be a valid update the shred users of the parent and
14506     * the children should match. We may later support changing child shared users.
14507     * @param oldPkg The updated package.
14508     * @param newPkg The update package.
14509     * @return The shared user that change between the versions.
14510     */
14511    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14512            PackageParser.Package newPkg) {
14513        // Check parent shared user
14514        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14515            return newPkg.packageName;
14516        }
14517        // Check child shared users
14518        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14519        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14520        for (int i = 0; i < newChildCount; i++) {
14521            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14522            // If this child was present, did it have the same shared user?
14523            for (int j = 0; j < oldChildCount; j++) {
14524                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14525                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14526                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14527                    return newChildPkg.packageName;
14528                }
14529            }
14530        }
14531        return null;
14532    }
14533
14534    private void removeNativeBinariesLI(PackageSetting ps) {
14535        // Remove the lib path for the parent package
14536        if (ps != null) {
14537            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14538            // Remove the lib path for the child packages
14539            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14540            for (int i = 0; i < childCount; i++) {
14541                PackageSetting childPs = null;
14542                synchronized (mPackages) {
14543                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14544                }
14545                if (childPs != null) {
14546                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14547                            .legacyNativeLibraryPathString);
14548                }
14549            }
14550        }
14551    }
14552
14553    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14554        // Enable the parent package
14555        mSettings.enableSystemPackageLPw(pkg.packageName);
14556        // Enable the child packages
14557        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14558        for (int i = 0; i < childCount; i++) {
14559            PackageParser.Package childPkg = pkg.childPackages.get(i);
14560            mSettings.enableSystemPackageLPw(childPkg.packageName);
14561        }
14562    }
14563
14564    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14565            PackageParser.Package newPkg) {
14566        // Disable the parent package (parent always replaced)
14567        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14568        // Disable the child packages
14569        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14570        for (int i = 0; i < childCount; i++) {
14571            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14572            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14573            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14574        }
14575        return disabled;
14576    }
14577
14578    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14579            String installerPackageName) {
14580        // Enable the parent package
14581        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14582        // Enable the child packages
14583        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14584        for (int i = 0; i < childCount; i++) {
14585            PackageParser.Package childPkg = pkg.childPackages.get(i);
14586            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14587        }
14588    }
14589
14590    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14591        // Collect all used permissions in the UID
14592        ArraySet<String> usedPermissions = new ArraySet<>();
14593        final int packageCount = su.packages.size();
14594        for (int i = 0; i < packageCount; i++) {
14595            PackageSetting ps = su.packages.valueAt(i);
14596            if (ps.pkg == null) {
14597                continue;
14598            }
14599            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14600            for (int j = 0; j < requestedPermCount; j++) {
14601                String permission = ps.pkg.requestedPermissions.get(j);
14602                BasePermission bp = mSettings.mPermissions.get(permission);
14603                if (bp != null) {
14604                    usedPermissions.add(permission);
14605                }
14606            }
14607        }
14608
14609        PermissionsState permissionsState = su.getPermissionsState();
14610        // Prune install permissions
14611        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14612        final int installPermCount = installPermStates.size();
14613        for (int i = installPermCount - 1; i >= 0;  i--) {
14614            PermissionState permissionState = installPermStates.get(i);
14615            if (!usedPermissions.contains(permissionState.getName())) {
14616                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14617                if (bp != null) {
14618                    permissionsState.revokeInstallPermission(bp);
14619                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14620                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14621                }
14622            }
14623        }
14624
14625        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14626
14627        // Prune runtime permissions
14628        for (int userId : allUserIds) {
14629            List<PermissionState> runtimePermStates = permissionsState
14630                    .getRuntimePermissionStates(userId);
14631            final int runtimePermCount = runtimePermStates.size();
14632            for (int i = runtimePermCount - 1; i >= 0; i--) {
14633                PermissionState permissionState = runtimePermStates.get(i);
14634                if (!usedPermissions.contains(permissionState.getName())) {
14635                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14636                    if (bp != null) {
14637                        permissionsState.revokeRuntimePermission(bp, userId);
14638                        permissionsState.updatePermissionFlags(bp, userId,
14639                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14640                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14641                                runtimePermissionChangedUserIds, userId);
14642                    }
14643                }
14644            }
14645        }
14646
14647        return runtimePermissionChangedUserIds;
14648    }
14649
14650    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14651            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14652        // Update the parent package setting
14653        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14654                res, user);
14655        // Update the child packages setting
14656        final int childCount = (newPackage.childPackages != null)
14657                ? newPackage.childPackages.size() : 0;
14658        for (int i = 0; i < childCount; i++) {
14659            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14660            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14661            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14662                    childRes.origUsers, childRes, user);
14663        }
14664    }
14665
14666    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14667            String installerPackageName, int[] allUsers, int[] installedForUsers,
14668            PackageInstalledInfo res, UserHandle user) {
14669        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14670
14671        String pkgName = newPackage.packageName;
14672        synchronized (mPackages) {
14673            //write settings. the installStatus will be incomplete at this stage.
14674            //note that the new package setting would have already been
14675            //added to mPackages. It hasn't been persisted yet.
14676            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14677            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14678            mSettings.writeLPr();
14679            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14680        }
14681
14682        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14683        synchronized (mPackages) {
14684            updatePermissionsLPw(newPackage.packageName, newPackage,
14685                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14686                            ? UPDATE_PERMISSIONS_ALL : 0));
14687            // For system-bundled packages, we assume that installing an upgraded version
14688            // of the package implies that the user actually wants to run that new code,
14689            // so we enable the package.
14690            PackageSetting ps = mSettings.mPackages.get(pkgName);
14691            final int userId = user.getIdentifier();
14692            if (ps != null) {
14693                if (isSystemApp(newPackage)) {
14694                    if (DEBUG_INSTALL) {
14695                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14696                    }
14697                    // Enable system package for requested users
14698                    if (res.origUsers != null) {
14699                        for (int origUserId : res.origUsers) {
14700                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14701                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14702                                        origUserId, installerPackageName);
14703                            }
14704                        }
14705                    }
14706                    // Also convey the prior install/uninstall state
14707                    if (allUsers != null && installedForUsers != null) {
14708                        for (int currentUserId : allUsers) {
14709                            final boolean installed = ArrayUtils.contains(
14710                                    installedForUsers, currentUserId);
14711                            if (DEBUG_INSTALL) {
14712                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14713                            }
14714                            ps.setInstalled(installed, currentUserId);
14715                        }
14716                        // these install state changes will be persisted in the
14717                        // upcoming call to mSettings.writeLPr().
14718                    }
14719                }
14720                // It's implied that when a user requests installation, they want the app to be
14721                // installed and enabled.
14722                if (userId != UserHandle.USER_ALL) {
14723                    ps.setInstalled(true, userId);
14724                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14725                }
14726            }
14727            res.name = pkgName;
14728            res.uid = newPackage.applicationInfo.uid;
14729            res.pkg = newPackage;
14730            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14731            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14732            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14733            //to update install status
14734            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14735            mSettings.writeLPr();
14736            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14737        }
14738
14739        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14740    }
14741
14742    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14743        try {
14744            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14745            installPackageLI(args, res);
14746        } finally {
14747            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14748        }
14749    }
14750
14751    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14752        final int installFlags = args.installFlags;
14753        final String installerPackageName = args.installerPackageName;
14754        final String volumeUuid = args.volumeUuid;
14755        final File tmpPackageFile = new File(args.getCodePath());
14756        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14757        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14758                || (args.volumeUuid != null));
14759        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14760        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14761        boolean replace = false;
14762        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14763        if (args.move != null) {
14764            // moving a complete application; perform an initial scan on the new install location
14765            scanFlags |= SCAN_INITIAL;
14766        }
14767        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14768            scanFlags |= SCAN_DONT_KILL_APP;
14769        }
14770
14771        // Result object to be returned
14772        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14773
14774        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14775
14776        // Sanity check
14777        if (ephemeral && (forwardLocked || onExternal)) {
14778            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14779                    + " external=" + onExternal);
14780            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14781            return;
14782        }
14783
14784        // Retrieve PackageSettings and parse package
14785        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14786                | PackageParser.PARSE_ENFORCE_CODE
14787                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14788                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14789                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14790                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14791        PackageParser pp = new PackageParser();
14792        pp.setSeparateProcesses(mSeparateProcesses);
14793        pp.setDisplayMetrics(mMetrics);
14794
14795        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14796        final PackageParser.Package pkg;
14797        try {
14798            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14799        } catch (PackageParserException e) {
14800            res.setError("Failed parse during installPackageLI", e);
14801            return;
14802        } finally {
14803            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14804        }
14805
14806        // If we are installing a clustered package add results for the children
14807        if (pkg.childPackages != null) {
14808            synchronized (mPackages) {
14809                final int childCount = pkg.childPackages.size();
14810                for (int i = 0; i < childCount; i++) {
14811                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14812                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14813                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14814                    childRes.pkg = childPkg;
14815                    childRes.name = childPkg.packageName;
14816                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14817                    if (childPs != null) {
14818                        childRes.origUsers = childPs.queryInstalledUsers(
14819                                sUserManager.getUserIds(), true);
14820                    }
14821                    if ((mPackages.containsKey(childPkg.packageName))) {
14822                        childRes.removedInfo = new PackageRemovedInfo();
14823                        childRes.removedInfo.removedPackage = childPkg.packageName;
14824                    }
14825                    if (res.addedChildPackages == null) {
14826                        res.addedChildPackages = new ArrayMap<>();
14827                    }
14828                    res.addedChildPackages.put(childPkg.packageName, childRes);
14829                }
14830            }
14831        }
14832
14833        // If package doesn't declare API override, mark that we have an install
14834        // time CPU ABI override.
14835        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14836            pkg.cpuAbiOverride = args.abiOverride;
14837        }
14838
14839        String pkgName = res.name = pkg.packageName;
14840        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14841            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14842                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14843                return;
14844            }
14845        }
14846
14847        try {
14848            // either use what we've been given or parse directly from the APK
14849            if (args.certificates != null) {
14850                try {
14851                    PackageParser.populateCertificates(pkg, args.certificates);
14852                } catch (PackageParserException e) {
14853                    // there was something wrong with the certificates we were given;
14854                    // try to pull them from the APK
14855                    PackageParser.collectCertificates(pkg, parseFlags);
14856                }
14857            } else {
14858                PackageParser.collectCertificates(pkg, parseFlags);
14859            }
14860        } catch (PackageParserException e) {
14861            res.setError("Failed collect during installPackageLI", e);
14862            return;
14863        }
14864
14865        // Get rid of all references to package scan path via parser.
14866        pp = null;
14867        String oldCodePath = null;
14868        boolean systemApp = false;
14869        synchronized (mPackages) {
14870            // Check if installing already existing package
14871            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14872                String oldName = mSettings.mRenamedPackages.get(pkgName);
14873                if (pkg.mOriginalPackages != null
14874                        && pkg.mOriginalPackages.contains(oldName)
14875                        && mPackages.containsKey(oldName)) {
14876                    // This package is derived from an original package,
14877                    // and this device has been updating from that original
14878                    // name.  We must continue using the original name, so
14879                    // rename the new package here.
14880                    pkg.setPackageName(oldName);
14881                    pkgName = pkg.packageName;
14882                    replace = true;
14883                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14884                            + oldName + " pkgName=" + pkgName);
14885                } else if (mPackages.containsKey(pkgName)) {
14886                    // This package, under its official name, already exists
14887                    // on the device; we should replace it.
14888                    replace = true;
14889                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14890                }
14891
14892                // Child packages are installed through the parent package
14893                if (pkg.parentPackage != null) {
14894                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14895                            "Package " + pkg.packageName + " is child of package "
14896                                    + pkg.parentPackage.parentPackage + ". Child packages "
14897                                    + "can be updated only through the parent package.");
14898                    return;
14899                }
14900
14901                if (replace) {
14902                    // Prevent apps opting out from runtime permissions
14903                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14904                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14905                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14906                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14907                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14908                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14909                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14910                                        + " doesn't support runtime permissions but the old"
14911                                        + " target SDK " + oldTargetSdk + " does.");
14912                        return;
14913                    }
14914
14915                    // Prevent installing of child packages
14916                    if (oldPackage.parentPackage != null) {
14917                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14918                                "Package " + pkg.packageName + " is child of package "
14919                                        + oldPackage.parentPackage + ". Child packages "
14920                                        + "can be updated only through the parent package.");
14921                        return;
14922                    }
14923                }
14924            }
14925
14926            PackageSetting ps = mSettings.mPackages.get(pkgName);
14927            if (ps != null) {
14928                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14929
14930                // Quick sanity check that we're signed correctly if updating;
14931                // we'll check this again later when scanning, but we want to
14932                // bail early here before tripping over redefined permissions.
14933                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14934                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14935                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14936                                + pkg.packageName + " upgrade keys do not match the "
14937                                + "previously installed version");
14938                        return;
14939                    }
14940                } else {
14941                    try {
14942                        verifySignaturesLP(ps, pkg);
14943                    } catch (PackageManagerException e) {
14944                        res.setError(e.error, e.getMessage());
14945                        return;
14946                    }
14947                }
14948
14949                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14950                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14951                    systemApp = (ps.pkg.applicationInfo.flags &
14952                            ApplicationInfo.FLAG_SYSTEM) != 0;
14953                }
14954                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14955            }
14956
14957            // Check whether the newly-scanned package wants to define an already-defined perm
14958            int N = pkg.permissions.size();
14959            for (int i = N-1; i >= 0; i--) {
14960                PackageParser.Permission perm = pkg.permissions.get(i);
14961                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14962                if (bp != null) {
14963                    // If the defining package is signed with our cert, it's okay.  This
14964                    // also includes the "updating the same package" case, of course.
14965                    // "updating same package" could also involve key-rotation.
14966                    final boolean sigsOk;
14967                    if (bp.sourcePackage.equals(pkg.packageName)
14968                            && (bp.packageSetting instanceof PackageSetting)
14969                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14970                                    scanFlags))) {
14971                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14972                    } else {
14973                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14974                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14975                    }
14976                    if (!sigsOk) {
14977                        // If the owning package is the system itself, we log but allow
14978                        // install to proceed; we fail the install on all other permission
14979                        // redefinitions.
14980                        if (!bp.sourcePackage.equals("android")) {
14981                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14982                                    + pkg.packageName + " attempting to redeclare permission "
14983                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14984                            res.origPermission = perm.info.name;
14985                            res.origPackage = bp.sourcePackage;
14986                            return;
14987                        } else {
14988                            Slog.w(TAG, "Package " + pkg.packageName
14989                                    + " attempting to redeclare system permission "
14990                                    + perm.info.name + "; ignoring new declaration");
14991                            pkg.permissions.remove(i);
14992                        }
14993                    }
14994                }
14995            }
14996        }
14997
14998        if (systemApp) {
14999            if (onExternal) {
15000                // Abort update; system app can't be replaced with app on sdcard
15001                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15002                        "Cannot install updates to system apps on sdcard");
15003                return;
15004            } else if (ephemeral) {
15005                // Abort update; system app can't be replaced with an ephemeral app
15006                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15007                        "Cannot update a system app with an ephemeral app");
15008                return;
15009            }
15010        }
15011
15012        if (args.move != null) {
15013            // We did an in-place move, so dex is ready to roll
15014            scanFlags |= SCAN_NO_DEX;
15015            scanFlags |= SCAN_MOVE;
15016
15017            synchronized (mPackages) {
15018                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15019                if (ps == null) {
15020                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15021                            "Missing settings for moved package " + pkgName);
15022                }
15023
15024                // We moved the entire application as-is, so bring over the
15025                // previously derived ABI information.
15026                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15027                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15028            }
15029
15030        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15031            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15032            scanFlags |= SCAN_NO_DEX;
15033
15034            try {
15035                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15036                    args.abiOverride : pkg.cpuAbiOverride);
15037                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15038                        true /* extract libs */);
15039            } catch (PackageManagerException pme) {
15040                Slog.e(TAG, "Error deriving application ABI", pme);
15041                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15042                return;
15043            }
15044
15045            // Shared libraries for the package need to be updated.
15046            synchronized (mPackages) {
15047                try {
15048                    updateSharedLibrariesLPw(pkg, null);
15049                } catch (PackageManagerException e) {
15050                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15051                }
15052            }
15053            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15054            // Do not run PackageDexOptimizer through the local performDexOpt
15055            // method because `pkg` may not be in `mPackages` yet.
15056            //
15057            // Also, don't fail application installs if the dexopt step fails.
15058            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15059                    null /* instructionSets */, false /* checkProfiles */,
15060                    getCompilerFilterForReason(REASON_INSTALL),
15061                    getOrCreateCompilerPackageStats(pkg));
15062            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15063
15064            // Notify BackgroundDexOptService that the package has been changed.
15065            // If this is an update of a package which used to fail to compile,
15066            // BDOS will remove it from its blacklist.
15067            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15068        }
15069
15070        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15071            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15072            return;
15073        }
15074
15075        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15076
15077        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15078                "installPackageLI")) {
15079            if (replace) {
15080                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15081                        installerPackageName, res);
15082            } else {
15083                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15084                        args.user, installerPackageName, volumeUuid, res);
15085            }
15086        }
15087        synchronized (mPackages) {
15088            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15089            if (ps != null) {
15090                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15091            }
15092
15093            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15094            for (int i = 0; i < childCount; i++) {
15095                PackageParser.Package childPkg = pkg.childPackages.get(i);
15096                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15097                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15098                if (childPs != null) {
15099                    childRes.newUsers = childPs.queryInstalledUsers(
15100                            sUserManager.getUserIds(), true);
15101                }
15102            }
15103        }
15104    }
15105
15106    private void startIntentFilterVerifications(int userId, boolean replacing,
15107            PackageParser.Package pkg) {
15108        if (mIntentFilterVerifierComponent == null) {
15109            Slog.w(TAG, "No IntentFilter verification will not be done as "
15110                    + "there is no IntentFilterVerifier available!");
15111            return;
15112        }
15113
15114        final int verifierUid = getPackageUid(
15115                mIntentFilterVerifierComponent.getPackageName(),
15116                MATCH_DEBUG_TRIAGED_MISSING,
15117                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15118
15119        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15120        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15121        mHandler.sendMessage(msg);
15122
15123        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15124        for (int i = 0; i < childCount; i++) {
15125            PackageParser.Package childPkg = pkg.childPackages.get(i);
15126            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15127            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15128            mHandler.sendMessage(msg);
15129        }
15130    }
15131
15132    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15133            PackageParser.Package pkg) {
15134        int size = pkg.activities.size();
15135        if (size == 0) {
15136            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15137                    "No activity, so no need to verify any IntentFilter!");
15138            return;
15139        }
15140
15141        final boolean hasDomainURLs = hasDomainURLs(pkg);
15142        if (!hasDomainURLs) {
15143            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15144                    "No domain URLs, so no need to verify any IntentFilter!");
15145            return;
15146        }
15147
15148        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15149                + " if any IntentFilter from the " + size
15150                + " Activities needs verification ...");
15151
15152        int count = 0;
15153        final String packageName = pkg.packageName;
15154
15155        synchronized (mPackages) {
15156            // If this is a new install and we see that we've already run verification for this
15157            // package, we have nothing to do: it means the state was restored from backup.
15158            if (!replacing) {
15159                IntentFilterVerificationInfo ivi =
15160                        mSettings.getIntentFilterVerificationLPr(packageName);
15161                if (ivi != null) {
15162                    if (DEBUG_DOMAIN_VERIFICATION) {
15163                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15164                                + ivi.getStatusString());
15165                    }
15166                    return;
15167                }
15168            }
15169
15170            // If any filters need to be verified, then all need to be.
15171            boolean needToVerify = false;
15172            for (PackageParser.Activity a : pkg.activities) {
15173                for (ActivityIntentInfo filter : a.intents) {
15174                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15175                        if (DEBUG_DOMAIN_VERIFICATION) {
15176                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15177                        }
15178                        needToVerify = true;
15179                        break;
15180                    }
15181                }
15182            }
15183
15184            if (needToVerify) {
15185                final int verificationId = mIntentFilterVerificationToken++;
15186                for (PackageParser.Activity a : pkg.activities) {
15187                    for (ActivityIntentInfo filter : a.intents) {
15188                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15189                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15190                                    "Verification needed for IntentFilter:" + filter.toString());
15191                            mIntentFilterVerifier.addOneIntentFilterVerification(
15192                                    verifierUid, userId, verificationId, filter, packageName);
15193                            count++;
15194                        }
15195                    }
15196                }
15197            }
15198        }
15199
15200        if (count > 0) {
15201            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15202                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15203                    +  " for userId:" + userId);
15204            mIntentFilterVerifier.startVerifications(userId);
15205        } else {
15206            if (DEBUG_DOMAIN_VERIFICATION) {
15207                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15208            }
15209        }
15210    }
15211
15212    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15213        final ComponentName cn  = filter.activity.getComponentName();
15214        final String packageName = cn.getPackageName();
15215
15216        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15217                packageName);
15218        if (ivi == null) {
15219            return true;
15220        }
15221        int status = ivi.getStatus();
15222        switch (status) {
15223            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15224            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15225                return true;
15226
15227            default:
15228                // Nothing to do
15229                return false;
15230        }
15231    }
15232
15233    private static boolean isMultiArch(ApplicationInfo info) {
15234        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15235    }
15236
15237    private static boolean isExternal(PackageParser.Package pkg) {
15238        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15239    }
15240
15241    private static boolean isExternal(PackageSetting ps) {
15242        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15243    }
15244
15245    private static boolean isEphemeral(PackageParser.Package pkg) {
15246        return pkg.applicationInfo.isEphemeralApp();
15247    }
15248
15249    private static boolean isEphemeral(PackageSetting ps) {
15250        return ps.pkg != null && isEphemeral(ps.pkg);
15251    }
15252
15253    private static boolean isSystemApp(PackageParser.Package pkg) {
15254        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15255    }
15256
15257    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15258        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15259    }
15260
15261    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15262        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15263    }
15264
15265    private static boolean isSystemApp(PackageSetting ps) {
15266        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15267    }
15268
15269    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15270        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15271    }
15272
15273    private int packageFlagsToInstallFlags(PackageSetting ps) {
15274        int installFlags = 0;
15275        if (isEphemeral(ps)) {
15276            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15277        }
15278        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15279            // This existing package was an external ASEC install when we have
15280            // the external flag without a UUID
15281            installFlags |= PackageManager.INSTALL_EXTERNAL;
15282        }
15283        if (ps.isForwardLocked()) {
15284            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15285        }
15286        return installFlags;
15287    }
15288
15289    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15290        if (isExternal(pkg)) {
15291            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15292                return StorageManager.UUID_PRIMARY_PHYSICAL;
15293            } else {
15294                return pkg.volumeUuid;
15295            }
15296        } else {
15297            return StorageManager.UUID_PRIVATE_INTERNAL;
15298        }
15299    }
15300
15301    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15302        if (isExternal(pkg)) {
15303            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15304                return mSettings.getExternalVersion();
15305            } else {
15306                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15307            }
15308        } else {
15309            return mSettings.getInternalVersion();
15310        }
15311    }
15312
15313    private void deleteTempPackageFiles() {
15314        final FilenameFilter filter = new FilenameFilter() {
15315            public boolean accept(File dir, String name) {
15316                return name.startsWith("vmdl") && name.endsWith(".tmp");
15317            }
15318        };
15319        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15320            file.delete();
15321        }
15322    }
15323
15324    @Override
15325    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15326            int flags) {
15327        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15328                flags);
15329    }
15330
15331    @Override
15332    public void deletePackage(final String packageName,
15333            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15334        mContext.enforceCallingOrSelfPermission(
15335                android.Manifest.permission.DELETE_PACKAGES, null);
15336        Preconditions.checkNotNull(packageName);
15337        Preconditions.checkNotNull(observer);
15338        final int uid = Binder.getCallingUid();
15339        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15340        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15341        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15342            mContext.enforceCallingOrSelfPermission(
15343                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15344                    "deletePackage for user " + userId);
15345        }
15346
15347        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15348            try {
15349                observer.onPackageDeleted(packageName,
15350                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15351            } catch (RemoteException re) {
15352            }
15353            return;
15354        }
15355
15356        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15357            try {
15358                observer.onPackageDeleted(packageName,
15359                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15360            } catch (RemoteException re) {
15361            }
15362            return;
15363        }
15364
15365        if (DEBUG_REMOVE) {
15366            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15367                    + " deleteAllUsers: " + deleteAllUsers );
15368        }
15369        // Queue up an async operation since the package deletion may take a little while.
15370        mHandler.post(new Runnable() {
15371            public void run() {
15372                mHandler.removeCallbacks(this);
15373                int returnCode;
15374                if (!deleteAllUsers) {
15375                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15376                } else {
15377                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15378                    // If nobody is blocking uninstall, proceed with delete for all users
15379                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15380                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15381                    } else {
15382                        // Otherwise uninstall individually for users with blockUninstalls=false
15383                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15384                        for (int userId : users) {
15385                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15386                                returnCode = deletePackageX(packageName, userId, userFlags);
15387                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15388                                    Slog.w(TAG, "Package delete failed for user " + userId
15389                                            + ", returnCode " + returnCode);
15390                                }
15391                            }
15392                        }
15393                        // The app has only been marked uninstalled for certain users.
15394                        // We still need to report that delete was blocked
15395                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15396                    }
15397                }
15398                try {
15399                    observer.onPackageDeleted(packageName, returnCode, null);
15400                } catch (RemoteException e) {
15401                    Log.i(TAG, "Observer no longer exists.");
15402                } //end catch
15403            } //end run
15404        });
15405    }
15406
15407    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15408        int[] result = EMPTY_INT_ARRAY;
15409        for (int userId : userIds) {
15410            if (getBlockUninstallForUser(packageName, userId)) {
15411                result = ArrayUtils.appendInt(result, userId);
15412            }
15413        }
15414        return result;
15415    }
15416
15417    @Override
15418    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15419        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15420    }
15421
15422    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15423        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15424                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15425        try {
15426            if (dpm != null) {
15427                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15428                        /* callingUserOnly =*/ false);
15429                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15430                        : deviceOwnerComponentName.getPackageName();
15431                // Does the package contains the device owner?
15432                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15433                // this check is probably not needed, since DO should be registered as a device
15434                // admin on some user too. (Original bug for this: b/17657954)
15435                if (packageName.equals(deviceOwnerPackageName)) {
15436                    return true;
15437                }
15438                // Does it contain a device admin for any user?
15439                int[] users;
15440                if (userId == UserHandle.USER_ALL) {
15441                    users = sUserManager.getUserIds();
15442                } else {
15443                    users = new int[]{userId};
15444                }
15445                for (int i = 0; i < users.length; ++i) {
15446                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15447                        return true;
15448                    }
15449                }
15450            }
15451        } catch (RemoteException e) {
15452        }
15453        return false;
15454    }
15455
15456    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15457        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15458    }
15459
15460    /**
15461     *  This method is an internal method that could be get invoked either
15462     *  to delete an installed package or to clean up a failed installation.
15463     *  After deleting an installed package, a broadcast is sent to notify any
15464     *  listeners that the package has been removed. For cleaning up a failed
15465     *  installation, the broadcast is not necessary since the package's
15466     *  installation wouldn't have sent the initial broadcast either
15467     *  The key steps in deleting a package are
15468     *  deleting the package information in internal structures like mPackages,
15469     *  deleting the packages base directories through installd
15470     *  updating mSettings to reflect current status
15471     *  persisting settings for later use
15472     *  sending a broadcast if necessary
15473     */
15474    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15475        final PackageRemovedInfo info = new PackageRemovedInfo();
15476        final boolean res;
15477
15478        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15479                ? UserHandle.USER_ALL : userId;
15480
15481        if (isPackageDeviceAdmin(packageName, removeUser)) {
15482            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15483            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15484        }
15485
15486        PackageSetting uninstalledPs = null;
15487
15488        // for the uninstall-updates case and restricted profiles, remember the per-
15489        // user handle installed state
15490        int[] allUsers;
15491        synchronized (mPackages) {
15492            uninstalledPs = mSettings.mPackages.get(packageName);
15493            if (uninstalledPs == null) {
15494                Slog.w(TAG, "Not removing non-existent package " + packageName);
15495                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15496            }
15497            allUsers = sUserManager.getUserIds();
15498            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15499        }
15500
15501        final int freezeUser;
15502        if (isUpdatedSystemApp(uninstalledPs)
15503                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
15504            // We're downgrading a system app, which will apply to all users, so
15505            // freeze them all during the downgrade
15506            freezeUser = UserHandle.USER_ALL;
15507        } else {
15508            freezeUser = removeUser;
15509        }
15510
15511        synchronized (mInstallLock) {
15512            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15513            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
15514                    deleteFlags, "deletePackageX")) {
15515                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
15516                        deleteFlags | REMOVE_CHATTY, info, true, null);
15517            }
15518            synchronized (mPackages) {
15519                if (res) {
15520                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15521                }
15522            }
15523        }
15524
15525        if (res) {
15526            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15527            info.sendPackageRemovedBroadcasts(killApp);
15528            info.sendSystemPackageUpdatedBroadcasts();
15529            info.sendSystemPackageAppearedBroadcasts();
15530        }
15531        // Force a gc here.
15532        Runtime.getRuntime().gc();
15533        // Delete the resources here after sending the broadcast to let
15534        // other processes clean up before deleting resources.
15535        if (info.args != null) {
15536            synchronized (mInstallLock) {
15537                info.args.doPostDeleteLI(true);
15538            }
15539        }
15540
15541        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15542    }
15543
15544    class PackageRemovedInfo {
15545        String removedPackage;
15546        int uid = -1;
15547        int removedAppId = -1;
15548        int[] origUsers;
15549        int[] removedUsers = null;
15550        boolean isRemovedPackageSystemUpdate = false;
15551        boolean isUpdate;
15552        boolean dataRemoved;
15553        boolean removedForAllUsers;
15554        // Clean up resources deleted packages.
15555        InstallArgs args = null;
15556        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15557        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15558
15559        void sendPackageRemovedBroadcasts(boolean killApp) {
15560            sendPackageRemovedBroadcastInternal(killApp);
15561            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15562            for (int i = 0; i < childCount; i++) {
15563                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15564                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15565            }
15566        }
15567
15568        void sendSystemPackageUpdatedBroadcasts() {
15569            if (isRemovedPackageSystemUpdate) {
15570                sendSystemPackageUpdatedBroadcastsInternal();
15571                final int childCount = (removedChildPackages != null)
15572                        ? removedChildPackages.size() : 0;
15573                for (int i = 0; i < childCount; i++) {
15574                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15575                    if (childInfo.isRemovedPackageSystemUpdate) {
15576                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15577                    }
15578                }
15579            }
15580        }
15581
15582        void sendSystemPackageAppearedBroadcasts() {
15583            final int packageCount = (appearedChildPackages != null)
15584                    ? appearedChildPackages.size() : 0;
15585            for (int i = 0; i < packageCount; i++) {
15586                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15587                for (int userId : installedInfo.newUsers) {
15588                    sendPackageAddedForUser(installedInfo.name, true,
15589                            UserHandle.getAppId(installedInfo.uid), userId);
15590                }
15591            }
15592        }
15593
15594        private void sendSystemPackageUpdatedBroadcastsInternal() {
15595            Bundle extras = new Bundle(2);
15596            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15597            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15598            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15599                    extras, 0, null, null, null);
15600            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15601                    extras, 0, null, null, null);
15602            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15603                    null, 0, removedPackage, null, null);
15604        }
15605
15606        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15607            Bundle extras = new Bundle(2);
15608            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15609            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15610            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15611            if (isUpdate || isRemovedPackageSystemUpdate) {
15612                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15613            }
15614            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15615            if (removedPackage != null) {
15616                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15617                        extras, 0, null, null, removedUsers);
15618                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15619                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15620                            removedPackage, extras, 0, null, null, removedUsers);
15621                }
15622            }
15623            if (removedAppId >= 0) {
15624                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15625                        removedUsers);
15626            }
15627        }
15628    }
15629
15630    /*
15631     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15632     * flag is not set, the data directory is removed as well.
15633     * make sure this flag is set for partially installed apps. If not its meaningless to
15634     * delete a partially installed application.
15635     */
15636    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15637            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15638        String packageName = ps.name;
15639        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15640        // Retrieve object to delete permissions for shared user later on
15641        final PackageParser.Package deletedPkg;
15642        final PackageSetting deletedPs;
15643        // reader
15644        synchronized (mPackages) {
15645            deletedPkg = mPackages.get(packageName);
15646            deletedPs = mSettings.mPackages.get(packageName);
15647            if (outInfo != null) {
15648                outInfo.removedPackage = packageName;
15649                outInfo.removedUsers = deletedPs != null
15650                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15651                        : null;
15652            }
15653        }
15654
15655        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15656
15657        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15658            final PackageParser.Package resolvedPkg;
15659            if (deletedPkg != null) {
15660                resolvedPkg = deletedPkg;
15661            } else {
15662                // We don't have a parsed package when it lives on an ejected
15663                // adopted storage device, so fake something together
15664                resolvedPkg = new PackageParser.Package(ps.name);
15665                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15666            }
15667            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15668                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15669            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15670            if (outInfo != null) {
15671                outInfo.dataRemoved = true;
15672            }
15673            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15674        }
15675
15676        // writer
15677        synchronized (mPackages) {
15678            if (deletedPs != null) {
15679                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15680                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15681                    clearDefaultBrowserIfNeeded(packageName);
15682                    if (outInfo != null) {
15683                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15684                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15685                    }
15686                    updatePermissionsLPw(deletedPs.name, null, 0);
15687                    if (deletedPs.sharedUser != null) {
15688                        // Remove permissions associated with package. Since runtime
15689                        // permissions are per user we have to kill the removed package
15690                        // or packages running under the shared user of the removed
15691                        // package if revoking the permissions requested only by the removed
15692                        // package is successful and this causes a change in gids.
15693                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15694                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15695                                    userId);
15696                            if (userIdToKill == UserHandle.USER_ALL
15697                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15698                                // If gids changed for this user, kill all affected packages.
15699                                mHandler.post(new Runnable() {
15700                                    @Override
15701                                    public void run() {
15702                                        // This has to happen with no lock held.
15703                                        killApplication(deletedPs.name, deletedPs.appId,
15704                                                KILL_APP_REASON_GIDS_CHANGED);
15705                                    }
15706                                });
15707                                break;
15708                            }
15709                        }
15710                    }
15711                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15712                }
15713                // make sure to preserve per-user disabled state if this removal was just
15714                // a downgrade of a system app to the factory package
15715                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15716                    if (DEBUG_REMOVE) {
15717                        Slog.d(TAG, "Propagating install state across downgrade");
15718                    }
15719                    for (int userId : allUserHandles) {
15720                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15721                        if (DEBUG_REMOVE) {
15722                            Slog.d(TAG, "    user " + userId + " => " + installed);
15723                        }
15724                        ps.setInstalled(installed, userId);
15725                    }
15726                }
15727            }
15728            // can downgrade to reader
15729            if (writeSettings) {
15730                // Save settings now
15731                mSettings.writeLPr();
15732            }
15733        }
15734        if (outInfo != null) {
15735            // A user ID was deleted here. Go through all users and remove it
15736            // from KeyStore.
15737            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15738        }
15739    }
15740
15741    static boolean locationIsPrivileged(File path) {
15742        try {
15743            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15744                    .getCanonicalPath();
15745            return path.getCanonicalPath().startsWith(privilegedAppDir);
15746        } catch (IOException e) {
15747            Slog.e(TAG, "Unable to access code path " + path);
15748        }
15749        return false;
15750    }
15751
15752    /*
15753     * Tries to delete system package.
15754     */
15755    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15756            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15757            boolean writeSettings) {
15758        if (deletedPs.parentPackageName != null) {
15759            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15760            return false;
15761        }
15762
15763        final boolean applyUserRestrictions
15764                = (allUserHandles != null) && (outInfo.origUsers != null);
15765        final PackageSetting disabledPs;
15766        // Confirm if the system package has been updated
15767        // An updated system app can be deleted. This will also have to restore
15768        // the system pkg from system partition
15769        // reader
15770        synchronized (mPackages) {
15771            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15772        }
15773
15774        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15775                + " disabledPs=" + disabledPs);
15776
15777        if (disabledPs == null) {
15778            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15779            return false;
15780        } else if (DEBUG_REMOVE) {
15781            Slog.d(TAG, "Deleting system pkg from data partition");
15782        }
15783
15784        if (DEBUG_REMOVE) {
15785            if (applyUserRestrictions) {
15786                Slog.d(TAG, "Remembering install states:");
15787                for (int userId : allUserHandles) {
15788                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15789                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15790                }
15791            }
15792        }
15793
15794        // Delete the updated package
15795        outInfo.isRemovedPackageSystemUpdate = true;
15796        if (outInfo.removedChildPackages != null) {
15797            final int childCount = (deletedPs.childPackageNames != null)
15798                    ? deletedPs.childPackageNames.size() : 0;
15799            for (int i = 0; i < childCount; i++) {
15800                String childPackageName = deletedPs.childPackageNames.get(i);
15801                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15802                        .contains(childPackageName)) {
15803                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15804                            childPackageName);
15805                    if (childInfo != null) {
15806                        childInfo.isRemovedPackageSystemUpdate = true;
15807                    }
15808                }
15809            }
15810        }
15811
15812        if (disabledPs.versionCode < deletedPs.versionCode) {
15813            // Delete data for downgrades
15814            flags &= ~PackageManager.DELETE_KEEP_DATA;
15815        } else {
15816            // Preserve data by setting flag
15817            flags |= PackageManager.DELETE_KEEP_DATA;
15818        }
15819
15820        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15821                outInfo, writeSettings, disabledPs.pkg);
15822        if (!ret) {
15823            return false;
15824        }
15825
15826        // writer
15827        synchronized (mPackages) {
15828            // Reinstate the old system package
15829            enableSystemPackageLPw(disabledPs.pkg);
15830            // Remove any native libraries from the upgraded package.
15831            removeNativeBinariesLI(deletedPs);
15832        }
15833
15834        // Install the system package
15835        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15836        int parseFlags = mDefParseFlags
15837                | PackageParser.PARSE_MUST_BE_APK
15838                | PackageParser.PARSE_IS_SYSTEM
15839                | PackageParser.PARSE_IS_SYSTEM_DIR;
15840        if (locationIsPrivileged(disabledPs.codePath)) {
15841            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15842        }
15843
15844        final PackageParser.Package newPkg;
15845        try {
15846            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15847        } catch (PackageManagerException e) {
15848            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15849                    + e.getMessage());
15850            return false;
15851        }
15852
15853        prepareAppDataAfterInstallLIF(newPkg);
15854
15855        // writer
15856        synchronized (mPackages) {
15857            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15858
15859            // Propagate the permissions state as we do not want to drop on the floor
15860            // runtime permissions. The update permissions method below will take
15861            // care of removing obsolete permissions and grant install permissions.
15862            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15863            updatePermissionsLPw(newPkg.packageName, newPkg,
15864                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15865
15866            if (applyUserRestrictions) {
15867                if (DEBUG_REMOVE) {
15868                    Slog.d(TAG, "Propagating install state across reinstall");
15869                }
15870                for (int userId : allUserHandles) {
15871                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15872                    if (DEBUG_REMOVE) {
15873                        Slog.d(TAG, "    user " + userId + " => " + installed);
15874                    }
15875                    ps.setInstalled(installed, userId);
15876
15877                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15878                }
15879                // Regardless of writeSettings we need to ensure that this restriction
15880                // state propagation is persisted
15881                mSettings.writeAllUsersPackageRestrictionsLPr();
15882            }
15883            // can downgrade to reader here
15884            if (writeSettings) {
15885                mSettings.writeLPr();
15886            }
15887        }
15888        return true;
15889    }
15890
15891    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15892            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15893            PackageRemovedInfo outInfo, boolean writeSettings,
15894            PackageParser.Package replacingPackage) {
15895        synchronized (mPackages) {
15896            if (outInfo != null) {
15897                outInfo.uid = ps.appId;
15898            }
15899
15900            if (outInfo != null && outInfo.removedChildPackages != null) {
15901                final int childCount = (ps.childPackageNames != null)
15902                        ? ps.childPackageNames.size() : 0;
15903                for (int i = 0; i < childCount; i++) {
15904                    String childPackageName = ps.childPackageNames.get(i);
15905                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15906                    if (childPs == null) {
15907                        return false;
15908                    }
15909                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15910                            childPackageName);
15911                    if (childInfo != null) {
15912                        childInfo.uid = childPs.appId;
15913                    }
15914                }
15915            }
15916        }
15917
15918        // Delete package data from internal structures and also remove data if flag is set
15919        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15920
15921        // Delete the child packages data
15922        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15923        for (int i = 0; i < childCount; i++) {
15924            PackageSetting childPs;
15925            synchronized (mPackages) {
15926                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15927            }
15928            if (childPs != null) {
15929                PackageRemovedInfo childOutInfo = (outInfo != null
15930                        && outInfo.removedChildPackages != null)
15931                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15932                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15933                        && (replacingPackage != null
15934                        && !replacingPackage.hasChildPackage(childPs.name))
15935                        ? flags & ~DELETE_KEEP_DATA : flags;
15936                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
15937                        deleteFlags, writeSettings);
15938            }
15939        }
15940
15941        // Delete application code and resources only for parent packages
15942        if (ps.parentPackageName == null) {
15943            if (deleteCodeAndResources && (outInfo != null)) {
15944                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15945                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15946                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15947            }
15948        }
15949
15950        return true;
15951    }
15952
15953    @Override
15954    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15955            int userId) {
15956        mContext.enforceCallingOrSelfPermission(
15957                android.Manifest.permission.DELETE_PACKAGES, null);
15958        synchronized (mPackages) {
15959            PackageSetting ps = mSettings.mPackages.get(packageName);
15960            if (ps == null) {
15961                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15962                return false;
15963            }
15964            if (!ps.getInstalled(userId)) {
15965                // Can't block uninstall for an app that is not installed or enabled.
15966                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15967                return false;
15968            }
15969            ps.setBlockUninstall(blockUninstall, userId);
15970            mSettings.writePackageRestrictionsLPr(userId);
15971        }
15972        return true;
15973    }
15974
15975    @Override
15976    public boolean getBlockUninstallForUser(String packageName, int userId) {
15977        synchronized (mPackages) {
15978            PackageSetting ps = mSettings.mPackages.get(packageName);
15979            if (ps == null) {
15980                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15981                return false;
15982            }
15983            return ps.getBlockUninstall(userId);
15984        }
15985    }
15986
15987    @Override
15988    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15989        int callingUid = Binder.getCallingUid();
15990        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15991            throw new SecurityException(
15992                    "setRequiredForSystemUser can only be run by the system or root");
15993        }
15994        synchronized (mPackages) {
15995            PackageSetting ps = mSettings.mPackages.get(packageName);
15996            if (ps == null) {
15997                Log.w(TAG, "Package doesn't exist: " + packageName);
15998                return false;
15999            }
16000            if (systemUserApp) {
16001                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16002            } else {
16003                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16004            }
16005            mSettings.writeLPr();
16006        }
16007        return true;
16008    }
16009
16010    /*
16011     * This method handles package deletion in general
16012     */
16013    private boolean deletePackageLIF(String packageName, UserHandle user,
16014            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16015            PackageRemovedInfo outInfo, boolean writeSettings,
16016            PackageParser.Package replacingPackage) {
16017        if (packageName == null) {
16018            Slog.w(TAG, "Attempt to delete null packageName.");
16019            return false;
16020        }
16021
16022        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16023
16024        PackageSetting ps;
16025
16026        synchronized (mPackages) {
16027            ps = mSettings.mPackages.get(packageName);
16028            if (ps == null) {
16029                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16030                return false;
16031            }
16032
16033            if (ps.parentPackageName != null && (!isSystemApp(ps)
16034                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16035                if (DEBUG_REMOVE) {
16036                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16037                            + ((user == null) ? UserHandle.USER_ALL : user));
16038                }
16039                final int removedUserId = (user != null) ? user.getIdentifier()
16040                        : UserHandle.USER_ALL;
16041                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16042                    return false;
16043                }
16044                markPackageUninstalledForUserLPw(ps, user);
16045                scheduleWritePackageRestrictionsLocked(user);
16046                return true;
16047            }
16048        }
16049
16050        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16051                && user.getIdentifier() != UserHandle.USER_ALL)) {
16052            // The caller is asking that the package only be deleted for a single
16053            // user.  To do this, we just mark its uninstalled state and delete
16054            // its data. If this is a system app, we only allow this to happen if
16055            // they have set the special DELETE_SYSTEM_APP which requests different
16056            // semantics than normal for uninstalling system apps.
16057            markPackageUninstalledForUserLPw(ps, user);
16058
16059            if (!isSystemApp(ps)) {
16060                // Do not uninstall the APK if an app should be cached
16061                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16062                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16063                    // Other user still have this package installed, so all
16064                    // we need to do is clear this user's data and save that
16065                    // it is uninstalled.
16066                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16067                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16068                        return false;
16069                    }
16070                    scheduleWritePackageRestrictionsLocked(user);
16071                    return true;
16072                } else {
16073                    // We need to set it back to 'installed' so the uninstall
16074                    // broadcasts will be sent correctly.
16075                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16076                    ps.setInstalled(true, user.getIdentifier());
16077                }
16078            } else {
16079                // This is a system app, so we assume that the
16080                // other users still have this package installed, so all
16081                // we need to do is clear this user's data and save that
16082                // it is uninstalled.
16083                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16084                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16085                    return false;
16086                }
16087                scheduleWritePackageRestrictionsLocked(user);
16088                return true;
16089            }
16090        }
16091
16092        // If we are deleting a composite package for all users, keep track
16093        // of result for each child.
16094        if (ps.childPackageNames != null && outInfo != null) {
16095            synchronized (mPackages) {
16096                final int childCount = ps.childPackageNames.size();
16097                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16098                for (int i = 0; i < childCount; i++) {
16099                    String childPackageName = ps.childPackageNames.get(i);
16100                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16101                    childInfo.removedPackage = childPackageName;
16102                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16103                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16104                    if (childPs != null) {
16105                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16106                    }
16107                }
16108            }
16109        }
16110
16111        boolean ret = false;
16112        if (isSystemApp(ps)) {
16113            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16114            // When an updated system application is deleted we delete the existing resources
16115            // as well and fall back to existing code in system partition
16116            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16117        } else {
16118            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16119            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16120                    outInfo, writeSettings, replacingPackage);
16121        }
16122
16123        // Take a note whether we deleted the package for all users
16124        if (outInfo != null) {
16125            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16126            if (outInfo.removedChildPackages != null) {
16127                synchronized (mPackages) {
16128                    final int childCount = outInfo.removedChildPackages.size();
16129                    for (int i = 0; i < childCount; i++) {
16130                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16131                        if (childInfo != null) {
16132                            childInfo.removedForAllUsers = mPackages.get(
16133                                    childInfo.removedPackage) == null;
16134                        }
16135                    }
16136                }
16137            }
16138            // If we uninstalled an update to a system app there may be some
16139            // child packages that appeared as they are declared in the system
16140            // app but were not declared in the update.
16141            if (isSystemApp(ps)) {
16142                synchronized (mPackages) {
16143                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16144                    final int childCount = (updatedPs.childPackageNames != null)
16145                            ? updatedPs.childPackageNames.size() : 0;
16146                    for (int i = 0; i < childCount; i++) {
16147                        String childPackageName = updatedPs.childPackageNames.get(i);
16148                        if (outInfo.removedChildPackages == null
16149                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16150                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16151                            if (childPs == null) {
16152                                continue;
16153                            }
16154                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16155                            installRes.name = childPackageName;
16156                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16157                            installRes.pkg = mPackages.get(childPackageName);
16158                            installRes.uid = childPs.pkg.applicationInfo.uid;
16159                            if (outInfo.appearedChildPackages == null) {
16160                                outInfo.appearedChildPackages = new ArrayMap<>();
16161                            }
16162                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16163                        }
16164                    }
16165                }
16166            }
16167        }
16168
16169        return ret;
16170    }
16171
16172    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16173        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16174                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16175        for (int nextUserId : userIds) {
16176            if (DEBUG_REMOVE) {
16177                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16178            }
16179            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16180                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16181                    false /*hidden*/, false /*suspended*/, null, null, null,
16182                    false /*blockUninstall*/,
16183                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16184        }
16185    }
16186
16187    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16188            PackageRemovedInfo outInfo) {
16189        final PackageParser.Package pkg;
16190        synchronized (mPackages) {
16191            pkg = mPackages.get(ps.name);
16192        }
16193
16194        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16195                : new int[] {userId};
16196        for (int nextUserId : userIds) {
16197            if (DEBUG_REMOVE) {
16198                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16199                        + nextUserId);
16200            }
16201
16202            destroyAppDataLIF(pkg, userId,
16203                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16204            destroyAppProfilesLIF(pkg, userId);
16205            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16206            schedulePackageCleaning(ps.name, nextUserId, false);
16207            synchronized (mPackages) {
16208                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16209                    scheduleWritePackageRestrictionsLocked(nextUserId);
16210                }
16211                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16212            }
16213        }
16214
16215        if (outInfo != null) {
16216            outInfo.removedPackage = ps.name;
16217            outInfo.removedAppId = ps.appId;
16218            outInfo.removedUsers = userIds;
16219        }
16220
16221        return true;
16222    }
16223
16224    private final class ClearStorageConnection implements ServiceConnection {
16225        IMediaContainerService mContainerService;
16226
16227        @Override
16228        public void onServiceConnected(ComponentName name, IBinder service) {
16229            synchronized (this) {
16230                mContainerService = IMediaContainerService.Stub.asInterface(service);
16231                notifyAll();
16232            }
16233        }
16234
16235        @Override
16236        public void onServiceDisconnected(ComponentName name) {
16237        }
16238    }
16239
16240    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16241        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16242
16243        final boolean mounted;
16244        if (Environment.isExternalStorageEmulated()) {
16245            mounted = true;
16246        } else {
16247            final String status = Environment.getExternalStorageState();
16248
16249            mounted = status.equals(Environment.MEDIA_MOUNTED)
16250                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16251        }
16252
16253        if (!mounted) {
16254            return;
16255        }
16256
16257        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16258        int[] users;
16259        if (userId == UserHandle.USER_ALL) {
16260            users = sUserManager.getUserIds();
16261        } else {
16262            users = new int[] { userId };
16263        }
16264        final ClearStorageConnection conn = new ClearStorageConnection();
16265        if (mContext.bindServiceAsUser(
16266                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16267            try {
16268                for (int curUser : users) {
16269                    long timeout = SystemClock.uptimeMillis() + 5000;
16270                    synchronized (conn) {
16271                        long now;
16272                        while (conn.mContainerService == null &&
16273                                (now = SystemClock.uptimeMillis()) < timeout) {
16274                            try {
16275                                conn.wait(timeout - now);
16276                            } catch (InterruptedException e) {
16277                            }
16278                        }
16279                    }
16280                    if (conn.mContainerService == null) {
16281                        return;
16282                    }
16283
16284                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16285                    clearDirectory(conn.mContainerService,
16286                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16287                    if (allData) {
16288                        clearDirectory(conn.mContainerService,
16289                                userEnv.buildExternalStorageAppDataDirs(packageName));
16290                        clearDirectory(conn.mContainerService,
16291                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16292                    }
16293                }
16294            } finally {
16295                mContext.unbindService(conn);
16296            }
16297        }
16298    }
16299
16300    @Override
16301    public void clearApplicationProfileData(String packageName) {
16302        enforceSystemOrRoot("Only the system can clear all profile data");
16303
16304        final PackageParser.Package pkg;
16305        synchronized (mPackages) {
16306            pkg = mPackages.get(packageName);
16307        }
16308
16309        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16310            synchronized (mInstallLock) {
16311                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16312                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16313                        true /* removeBaseMarker */);
16314            }
16315        }
16316    }
16317
16318    @Override
16319    public void clearApplicationUserData(final String packageName,
16320            final IPackageDataObserver observer, final int userId) {
16321        mContext.enforceCallingOrSelfPermission(
16322                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16323
16324        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16325                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16326
16327        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
16328            throw new SecurityException("Cannot clear data for a protected package: "
16329                    + packageName);
16330        }
16331        // Queue up an async operation since the package deletion may take a little while.
16332        mHandler.post(new Runnable() {
16333            public void run() {
16334                mHandler.removeCallbacks(this);
16335                final boolean succeeded;
16336                try (PackageFreezer freezer = freezePackage(packageName,
16337                        "clearApplicationUserData")) {
16338                    synchronized (mInstallLock) {
16339                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16340                    }
16341                    clearExternalStorageDataSync(packageName, userId, true);
16342                }
16343                if (succeeded) {
16344                    // invoke DeviceStorageMonitor's update method to clear any notifications
16345                    DeviceStorageMonitorInternal dsm = LocalServices
16346                            .getService(DeviceStorageMonitorInternal.class);
16347                    if (dsm != null) {
16348                        dsm.checkMemory();
16349                    }
16350                }
16351                if(observer != null) {
16352                    try {
16353                        observer.onRemoveCompleted(packageName, succeeded);
16354                    } catch (RemoteException e) {
16355                        Log.i(TAG, "Observer no longer exists.");
16356                    }
16357                } //end if observer
16358            } //end run
16359        });
16360    }
16361
16362    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16363        if (packageName == null) {
16364            Slog.w(TAG, "Attempt to delete null packageName.");
16365            return false;
16366        }
16367
16368        // Try finding details about the requested package
16369        PackageParser.Package pkg;
16370        synchronized (mPackages) {
16371            pkg = mPackages.get(packageName);
16372            if (pkg == null) {
16373                final PackageSetting ps = mSettings.mPackages.get(packageName);
16374                if (ps != null) {
16375                    pkg = ps.pkg;
16376                }
16377            }
16378
16379            if (pkg == null) {
16380                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16381                return false;
16382            }
16383
16384            PackageSetting ps = (PackageSetting) pkg.mExtras;
16385            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16386        }
16387
16388        clearAppDataLIF(pkg, userId,
16389                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16390
16391        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16392        removeKeystoreDataIfNeeded(userId, appId);
16393
16394        UserManagerInternal umInternal = getUserManagerInternal();
16395        final int flags;
16396        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16397            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16398        } else if (umInternal.isUserRunning(userId)) {
16399            flags = StorageManager.FLAG_STORAGE_DE;
16400        } else {
16401            flags = 0;
16402        }
16403        prepareAppDataContentsLIF(pkg, userId, flags);
16404
16405        return true;
16406    }
16407
16408    /**
16409     * Reverts user permission state changes (permissions and flags) in
16410     * all packages for a given user.
16411     *
16412     * @param userId The device user for which to do a reset.
16413     */
16414    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16415        final int packageCount = mPackages.size();
16416        for (int i = 0; i < packageCount; i++) {
16417            PackageParser.Package pkg = mPackages.valueAt(i);
16418            PackageSetting ps = (PackageSetting) pkg.mExtras;
16419            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16420        }
16421    }
16422
16423    private void resetNetworkPolicies(int userId) {
16424        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16425    }
16426
16427    /**
16428     * Reverts user permission state changes (permissions and flags).
16429     *
16430     * @param ps The package for which to reset.
16431     * @param userId The device user for which to do a reset.
16432     */
16433    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16434            final PackageSetting ps, final int userId) {
16435        if (ps.pkg == null) {
16436            return;
16437        }
16438
16439        // These are flags that can change base on user actions.
16440        final int userSettableMask = FLAG_PERMISSION_USER_SET
16441                | FLAG_PERMISSION_USER_FIXED
16442                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16443                | FLAG_PERMISSION_REVIEW_REQUIRED;
16444
16445        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16446                | FLAG_PERMISSION_POLICY_FIXED;
16447
16448        boolean writeInstallPermissions = false;
16449        boolean writeRuntimePermissions = false;
16450
16451        final int permissionCount = ps.pkg.requestedPermissions.size();
16452        for (int i = 0; i < permissionCount; i++) {
16453            String permission = ps.pkg.requestedPermissions.get(i);
16454
16455            BasePermission bp = mSettings.mPermissions.get(permission);
16456            if (bp == null) {
16457                continue;
16458            }
16459
16460            // If shared user we just reset the state to which only this app contributed.
16461            if (ps.sharedUser != null) {
16462                boolean used = false;
16463                final int packageCount = ps.sharedUser.packages.size();
16464                for (int j = 0; j < packageCount; j++) {
16465                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16466                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16467                            && pkg.pkg.requestedPermissions.contains(permission)) {
16468                        used = true;
16469                        break;
16470                    }
16471                }
16472                if (used) {
16473                    continue;
16474                }
16475            }
16476
16477            PermissionsState permissionsState = ps.getPermissionsState();
16478
16479            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16480
16481            // Always clear the user settable flags.
16482            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16483                    bp.name) != null;
16484            // If permission review is enabled and this is a legacy app, mark the
16485            // permission as requiring a review as this is the initial state.
16486            int flags = 0;
16487            if (Build.PERMISSIONS_REVIEW_REQUIRED
16488                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16489                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16490            }
16491            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16492                if (hasInstallState) {
16493                    writeInstallPermissions = true;
16494                } else {
16495                    writeRuntimePermissions = true;
16496                }
16497            }
16498
16499            // Below is only runtime permission handling.
16500            if (!bp.isRuntime()) {
16501                continue;
16502            }
16503
16504            // Never clobber system or policy.
16505            if ((oldFlags & policyOrSystemFlags) != 0) {
16506                continue;
16507            }
16508
16509            // If this permission was granted by default, make sure it is.
16510            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16511                if (permissionsState.grantRuntimePermission(bp, userId)
16512                        != PERMISSION_OPERATION_FAILURE) {
16513                    writeRuntimePermissions = true;
16514                }
16515            // If permission review is enabled the permissions for a legacy apps
16516            // are represented as constantly granted runtime ones, so don't revoke.
16517            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16518                // Otherwise, reset the permission.
16519                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16520                switch (revokeResult) {
16521                    case PERMISSION_OPERATION_SUCCESS:
16522                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16523                        writeRuntimePermissions = true;
16524                        final int appId = ps.appId;
16525                        mHandler.post(new Runnable() {
16526                            @Override
16527                            public void run() {
16528                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16529                            }
16530                        });
16531                    } break;
16532                }
16533            }
16534        }
16535
16536        // Synchronously write as we are taking permissions away.
16537        if (writeRuntimePermissions) {
16538            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16539        }
16540
16541        // Synchronously write as we are taking permissions away.
16542        if (writeInstallPermissions) {
16543            mSettings.writeLPr();
16544        }
16545    }
16546
16547    /**
16548     * Remove entries from the keystore daemon. Will only remove it if the
16549     * {@code appId} is valid.
16550     */
16551    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16552        if (appId < 0) {
16553            return;
16554        }
16555
16556        final KeyStore keyStore = KeyStore.getInstance();
16557        if (keyStore != null) {
16558            if (userId == UserHandle.USER_ALL) {
16559                for (final int individual : sUserManager.getUserIds()) {
16560                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16561                }
16562            } else {
16563                keyStore.clearUid(UserHandle.getUid(userId, appId));
16564            }
16565        } else {
16566            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16567        }
16568    }
16569
16570    @Override
16571    public void deleteApplicationCacheFiles(final String packageName,
16572            final IPackageDataObserver observer) {
16573        final int userId = UserHandle.getCallingUserId();
16574        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16575    }
16576
16577    @Override
16578    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16579            final IPackageDataObserver observer) {
16580        mContext.enforceCallingOrSelfPermission(
16581                android.Manifest.permission.DELETE_CACHE_FILES, null);
16582        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16583                /* requireFullPermission= */ true, /* checkShell= */ false,
16584                "delete application cache files");
16585
16586        final PackageParser.Package pkg;
16587        synchronized (mPackages) {
16588            pkg = mPackages.get(packageName);
16589        }
16590
16591        // Queue up an async operation since the package deletion may take a little while.
16592        mHandler.post(new Runnable() {
16593            public void run() {
16594                synchronized (mInstallLock) {
16595                    final int flags = StorageManager.FLAG_STORAGE_DE
16596                            | StorageManager.FLAG_STORAGE_CE;
16597                    // We're only clearing cache files, so we don't care if the
16598                    // app is unfrozen and still able to run
16599                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16600                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16601                }
16602                clearExternalStorageDataSync(packageName, userId, false);
16603                if (observer != null) {
16604                    try {
16605                        observer.onRemoveCompleted(packageName, true);
16606                    } catch (RemoteException e) {
16607                        Log.i(TAG, "Observer no longer exists.");
16608                    }
16609                }
16610            }
16611        });
16612    }
16613
16614    @Override
16615    public void getPackageSizeInfo(final String packageName, int userHandle,
16616            final IPackageStatsObserver observer) {
16617        mContext.enforceCallingOrSelfPermission(
16618                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16619        if (packageName == null) {
16620            throw new IllegalArgumentException("Attempt to get size of null packageName");
16621        }
16622
16623        PackageStats stats = new PackageStats(packageName, userHandle);
16624
16625        /*
16626         * Queue up an async operation since the package measurement may take a
16627         * little while.
16628         */
16629        Message msg = mHandler.obtainMessage(INIT_COPY);
16630        msg.obj = new MeasureParams(stats, observer);
16631        mHandler.sendMessage(msg);
16632    }
16633
16634    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16635        final PackageSetting ps;
16636        synchronized (mPackages) {
16637            ps = mSettings.mPackages.get(packageName);
16638            if (ps == null) {
16639                Slog.w(TAG, "Failed to find settings for " + packageName);
16640                return false;
16641            }
16642        }
16643        try {
16644            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16645                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16646                    ps.getCeDataInode(userId), ps.codePathString, stats);
16647        } catch (InstallerException e) {
16648            Slog.w(TAG, String.valueOf(e));
16649            return false;
16650        }
16651
16652        // For now, ignore code size of packages on system partition
16653        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16654            stats.codeSize = 0;
16655        }
16656
16657        return true;
16658    }
16659
16660    private int getUidTargetSdkVersionLockedLPr(int uid) {
16661        Object obj = mSettings.getUserIdLPr(uid);
16662        if (obj instanceof SharedUserSetting) {
16663            final SharedUserSetting sus = (SharedUserSetting) obj;
16664            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16665            final Iterator<PackageSetting> it = sus.packages.iterator();
16666            while (it.hasNext()) {
16667                final PackageSetting ps = it.next();
16668                if (ps.pkg != null) {
16669                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16670                    if (v < vers) vers = v;
16671                }
16672            }
16673            return vers;
16674        } else if (obj instanceof PackageSetting) {
16675            final PackageSetting ps = (PackageSetting) obj;
16676            if (ps.pkg != null) {
16677                return ps.pkg.applicationInfo.targetSdkVersion;
16678            }
16679        }
16680        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16681    }
16682
16683    @Override
16684    public void addPreferredActivity(IntentFilter filter, int match,
16685            ComponentName[] set, ComponentName activity, int userId) {
16686        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16687                "Adding preferred");
16688    }
16689
16690    private void addPreferredActivityInternal(IntentFilter filter, int match,
16691            ComponentName[] set, ComponentName activity, boolean always, int userId,
16692            String opname) {
16693        // writer
16694        int callingUid = Binder.getCallingUid();
16695        enforceCrossUserPermission(callingUid, userId,
16696                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16697        if (filter.countActions() == 0) {
16698            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16699            return;
16700        }
16701        synchronized (mPackages) {
16702            if (mContext.checkCallingOrSelfPermission(
16703                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16704                    != PackageManager.PERMISSION_GRANTED) {
16705                if (getUidTargetSdkVersionLockedLPr(callingUid)
16706                        < Build.VERSION_CODES.FROYO) {
16707                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16708                            + callingUid);
16709                    return;
16710                }
16711                mContext.enforceCallingOrSelfPermission(
16712                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16713            }
16714
16715            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16716            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16717                    + userId + ":");
16718            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16719            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16720            scheduleWritePackageRestrictionsLocked(userId);
16721            postPreferredActivityChangedBroadcast(userId);
16722        }
16723    }
16724
16725    private void postPreferredActivityChangedBroadcast(int userId) {
16726        mHandler.post(() -> {
16727            final IActivityManager am = ActivityManagerNative.getDefault();
16728            if (am == null) {
16729                return;
16730            }
16731
16732            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
16733            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
16734            try {
16735                am.broadcastIntent(null, intent, null, null,
16736                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
16737                        null, false, false, userId);
16738            } catch (RemoteException e) {
16739            }
16740        });
16741    }
16742
16743    @Override
16744    public void replacePreferredActivity(IntentFilter filter, int match,
16745            ComponentName[] set, ComponentName activity, int userId) {
16746        if (filter.countActions() != 1) {
16747            throw new IllegalArgumentException(
16748                    "replacePreferredActivity expects filter to have only 1 action.");
16749        }
16750        if (filter.countDataAuthorities() != 0
16751                || filter.countDataPaths() != 0
16752                || filter.countDataSchemes() > 1
16753                || filter.countDataTypes() != 0) {
16754            throw new IllegalArgumentException(
16755                    "replacePreferredActivity expects filter to have no data authorities, " +
16756                    "paths, or types; and at most one scheme.");
16757        }
16758
16759        final int callingUid = Binder.getCallingUid();
16760        enforceCrossUserPermission(callingUid, userId,
16761                true /* requireFullPermission */, false /* checkShell */,
16762                "replace preferred activity");
16763        synchronized (mPackages) {
16764            if (mContext.checkCallingOrSelfPermission(
16765                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16766                    != PackageManager.PERMISSION_GRANTED) {
16767                if (getUidTargetSdkVersionLockedLPr(callingUid)
16768                        < Build.VERSION_CODES.FROYO) {
16769                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16770                            + Binder.getCallingUid());
16771                    return;
16772                }
16773                mContext.enforceCallingOrSelfPermission(
16774                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16775            }
16776
16777            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16778            if (pir != null) {
16779                // Get all of the existing entries that exactly match this filter.
16780                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16781                if (existing != null && existing.size() == 1) {
16782                    PreferredActivity cur = existing.get(0);
16783                    if (DEBUG_PREFERRED) {
16784                        Slog.i(TAG, "Checking replace of preferred:");
16785                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16786                        if (!cur.mPref.mAlways) {
16787                            Slog.i(TAG, "  -- CUR; not mAlways!");
16788                        } else {
16789                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16790                            Slog.i(TAG, "  -- CUR: mSet="
16791                                    + Arrays.toString(cur.mPref.mSetComponents));
16792                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16793                            Slog.i(TAG, "  -- NEW: mMatch="
16794                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16795                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16796                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16797                        }
16798                    }
16799                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16800                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16801                            && cur.mPref.sameSet(set)) {
16802                        // Setting the preferred activity to what it happens to be already
16803                        if (DEBUG_PREFERRED) {
16804                            Slog.i(TAG, "Replacing with same preferred activity "
16805                                    + cur.mPref.mShortComponent + " for user "
16806                                    + userId + ":");
16807                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16808                        }
16809                        return;
16810                    }
16811                }
16812
16813                if (existing != null) {
16814                    if (DEBUG_PREFERRED) {
16815                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16816                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16817                    }
16818                    for (int i = 0; i < existing.size(); i++) {
16819                        PreferredActivity pa = existing.get(i);
16820                        if (DEBUG_PREFERRED) {
16821                            Slog.i(TAG, "Removing existing preferred activity "
16822                                    + pa.mPref.mComponent + ":");
16823                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16824                        }
16825                        pir.removeFilter(pa);
16826                    }
16827                }
16828            }
16829            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16830                    "Replacing preferred");
16831        }
16832    }
16833
16834    @Override
16835    public void clearPackagePreferredActivities(String packageName) {
16836        final int uid = Binder.getCallingUid();
16837        // writer
16838        synchronized (mPackages) {
16839            PackageParser.Package pkg = mPackages.get(packageName);
16840            if (pkg == null || pkg.applicationInfo.uid != uid) {
16841                if (mContext.checkCallingOrSelfPermission(
16842                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16843                        != PackageManager.PERMISSION_GRANTED) {
16844                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16845                            < Build.VERSION_CODES.FROYO) {
16846                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16847                                + Binder.getCallingUid());
16848                        return;
16849                    }
16850                    mContext.enforceCallingOrSelfPermission(
16851                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16852                }
16853            }
16854
16855            int user = UserHandle.getCallingUserId();
16856            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16857                scheduleWritePackageRestrictionsLocked(user);
16858            }
16859        }
16860    }
16861
16862    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16863    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16864        ArrayList<PreferredActivity> removed = null;
16865        boolean changed = false;
16866        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16867            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16868            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16869            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16870                continue;
16871            }
16872            Iterator<PreferredActivity> it = pir.filterIterator();
16873            while (it.hasNext()) {
16874                PreferredActivity pa = it.next();
16875                // Mark entry for removal only if it matches the package name
16876                // and the entry is of type "always".
16877                if (packageName == null ||
16878                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16879                                && pa.mPref.mAlways)) {
16880                    if (removed == null) {
16881                        removed = new ArrayList<PreferredActivity>();
16882                    }
16883                    removed.add(pa);
16884                }
16885            }
16886            if (removed != null) {
16887                for (int j=0; j<removed.size(); j++) {
16888                    PreferredActivity pa = removed.get(j);
16889                    pir.removeFilter(pa);
16890                }
16891                changed = true;
16892            }
16893        }
16894        if (changed) {
16895            postPreferredActivityChangedBroadcast(userId);
16896        }
16897        return changed;
16898    }
16899
16900    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16901    private void clearIntentFilterVerificationsLPw(int userId) {
16902        final int packageCount = mPackages.size();
16903        for (int i = 0; i < packageCount; i++) {
16904            PackageParser.Package pkg = mPackages.valueAt(i);
16905            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16906        }
16907    }
16908
16909    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16910    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16911        if (userId == UserHandle.USER_ALL) {
16912            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16913                    sUserManager.getUserIds())) {
16914                for (int oneUserId : sUserManager.getUserIds()) {
16915                    scheduleWritePackageRestrictionsLocked(oneUserId);
16916                }
16917            }
16918        } else {
16919            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16920                scheduleWritePackageRestrictionsLocked(userId);
16921            }
16922        }
16923    }
16924
16925    void clearDefaultBrowserIfNeeded(String packageName) {
16926        for (int oneUserId : sUserManager.getUserIds()) {
16927            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16928            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16929            if (packageName.equals(defaultBrowserPackageName)) {
16930                setDefaultBrowserPackageName(null, oneUserId);
16931            }
16932        }
16933    }
16934
16935    @Override
16936    public void resetApplicationPreferences(int userId) {
16937        mContext.enforceCallingOrSelfPermission(
16938                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16939        final long identity = Binder.clearCallingIdentity();
16940        // writer
16941        try {
16942            synchronized (mPackages) {
16943                clearPackagePreferredActivitiesLPw(null, userId);
16944                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16945                // TODO: We have to reset the default SMS and Phone. This requires
16946                // significant refactoring to keep all default apps in the package
16947                // manager (cleaner but more work) or have the services provide
16948                // callbacks to the package manager to request a default app reset.
16949                applyFactoryDefaultBrowserLPw(userId);
16950                clearIntentFilterVerificationsLPw(userId);
16951                primeDomainVerificationsLPw(userId);
16952                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16953                scheduleWritePackageRestrictionsLocked(userId);
16954            }
16955            resetNetworkPolicies(userId);
16956        } finally {
16957            Binder.restoreCallingIdentity(identity);
16958        }
16959    }
16960
16961    @Override
16962    public int getPreferredActivities(List<IntentFilter> outFilters,
16963            List<ComponentName> outActivities, String packageName) {
16964
16965        int num = 0;
16966        final int userId = UserHandle.getCallingUserId();
16967        // reader
16968        synchronized (mPackages) {
16969            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16970            if (pir != null) {
16971                final Iterator<PreferredActivity> it = pir.filterIterator();
16972                while (it.hasNext()) {
16973                    final PreferredActivity pa = it.next();
16974                    if (packageName == null
16975                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16976                                    && pa.mPref.mAlways)) {
16977                        if (outFilters != null) {
16978                            outFilters.add(new IntentFilter(pa));
16979                        }
16980                        if (outActivities != null) {
16981                            outActivities.add(pa.mPref.mComponent);
16982                        }
16983                    }
16984                }
16985            }
16986        }
16987
16988        return num;
16989    }
16990
16991    @Override
16992    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16993            int userId) {
16994        int callingUid = Binder.getCallingUid();
16995        if (callingUid != Process.SYSTEM_UID) {
16996            throw new SecurityException(
16997                    "addPersistentPreferredActivity can only be run by the system");
16998        }
16999        if (filter.countActions() == 0) {
17000            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17001            return;
17002        }
17003        synchronized (mPackages) {
17004            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17005                    ":");
17006            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17007            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17008                    new PersistentPreferredActivity(filter, activity));
17009            scheduleWritePackageRestrictionsLocked(userId);
17010            postPreferredActivityChangedBroadcast(userId);
17011        }
17012    }
17013
17014    @Override
17015    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17016        int callingUid = Binder.getCallingUid();
17017        if (callingUid != Process.SYSTEM_UID) {
17018            throw new SecurityException(
17019                    "clearPackagePersistentPreferredActivities can only be run by the system");
17020        }
17021        ArrayList<PersistentPreferredActivity> removed = null;
17022        boolean changed = false;
17023        synchronized (mPackages) {
17024            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17025                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17026                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17027                        .valueAt(i);
17028                if (userId != thisUserId) {
17029                    continue;
17030                }
17031                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17032                while (it.hasNext()) {
17033                    PersistentPreferredActivity ppa = it.next();
17034                    // Mark entry for removal only if it matches the package name.
17035                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17036                        if (removed == null) {
17037                            removed = new ArrayList<PersistentPreferredActivity>();
17038                        }
17039                        removed.add(ppa);
17040                    }
17041                }
17042                if (removed != null) {
17043                    for (int j=0; j<removed.size(); j++) {
17044                        PersistentPreferredActivity ppa = removed.get(j);
17045                        ppir.removeFilter(ppa);
17046                    }
17047                    changed = true;
17048                }
17049            }
17050
17051            if (changed) {
17052                scheduleWritePackageRestrictionsLocked(userId);
17053                postPreferredActivityChangedBroadcast(userId);
17054            }
17055        }
17056    }
17057
17058    /**
17059     * Common machinery for picking apart a restored XML blob and passing
17060     * it to a caller-supplied functor to be applied to the running system.
17061     */
17062    private void restoreFromXml(XmlPullParser parser, int userId,
17063            String expectedStartTag, BlobXmlRestorer functor)
17064            throws IOException, XmlPullParserException {
17065        int type;
17066        while ((type = parser.next()) != XmlPullParser.START_TAG
17067                && type != XmlPullParser.END_DOCUMENT) {
17068        }
17069        if (type != XmlPullParser.START_TAG) {
17070            // oops didn't find a start tag?!
17071            if (DEBUG_BACKUP) {
17072                Slog.e(TAG, "Didn't find start tag during restore");
17073            }
17074            return;
17075        }
17076Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17077        // this is supposed to be TAG_PREFERRED_BACKUP
17078        if (!expectedStartTag.equals(parser.getName())) {
17079            if (DEBUG_BACKUP) {
17080                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17081            }
17082            return;
17083        }
17084
17085        // skip interfering stuff, then we're aligned with the backing implementation
17086        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17087Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17088        functor.apply(parser, userId);
17089    }
17090
17091    private interface BlobXmlRestorer {
17092        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17093    }
17094
17095    /**
17096     * Non-Binder method, support for the backup/restore mechanism: write the
17097     * full set of preferred activities in its canonical XML format.  Returns the
17098     * XML output as a byte array, or null if there is none.
17099     */
17100    @Override
17101    public byte[] getPreferredActivityBackup(int userId) {
17102        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17103            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17104        }
17105
17106        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17107        try {
17108            final XmlSerializer serializer = new FastXmlSerializer();
17109            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17110            serializer.startDocument(null, true);
17111            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17112
17113            synchronized (mPackages) {
17114                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17115            }
17116
17117            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17118            serializer.endDocument();
17119            serializer.flush();
17120        } catch (Exception e) {
17121            if (DEBUG_BACKUP) {
17122                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17123            }
17124            return null;
17125        }
17126
17127        return dataStream.toByteArray();
17128    }
17129
17130    @Override
17131    public void restorePreferredActivities(byte[] backup, int userId) {
17132        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17133            throw new SecurityException("Only the system may call restorePreferredActivities()");
17134        }
17135
17136        try {
17137            final XmlPullParser parser = Xml.newPullParser();
17138            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17139            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17140                    new BlobXmlRestorer() {
17141                        @Override
17142                        public void apply(XmlPullParser parser, int userId)
17143                                throws XmlPullParserException, IOException {
17144                            synchronized (mPackages) {
17145                                mSettings.readPreferredActivitiesLPw(parser, userId);
17146                            }
17147                        }
17148                    } );
17149        } catch (Exception e) {
17150            if (DEBUG_BACKUP) {
17151                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17152            }
17153        }
17154    }
17155
17156    /**
17157     * Non-Binder method, support for the backup/restore mechanism: write the
17158     * default browser (etc) settings in its canonical XML format.  Returns the default
17159     * browser XML representation as a byte array, or null if there is none.
17160     */
17161    @Override
17162    public byte[] getDefaultAppsBackup(int userId) {
17163        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17164            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17165        }
17166
17167        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17168        try {
17169            final XmlSerializer serializer = new FastXmlSerializer();
17170            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17171            serializer.startDocument(null, true);
17172            serializer.startTag(null, TAG_DEFAULT_APPS);
17173
17174            synchronized (mPackages) {
17175                mSettings.writeDefaultAppsLPr(serializer, userId);
17176            }
17177
17178            serializer.endTag(null, TAG_DEFAULT_APPS);
17179            serializer.endDocument();
17180            serializer.flush();
17181        } catch (Exception e) {
17182            if (DEBUG_BACKUP) {
17183                Slog.e(TAG, "Unable to write default apps for backup", e);
17184            }
17185            return null;
17186        }
17187
17188        return dataStream.toByteArray();
17189    }
17190
17191    @Override
17192    public void restoreDefaultApps(byte[] backup, int userId) {
17193        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17194            throw new SecurityException("Only the system may call restoreDefaultApps()");
17195        }
17196
17197        try {
17198            final XmlPullParser parser = Xml.newPullParser();
17199            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17200            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17201                    new BlobXmlRestorer() {
17202                        @Override
17203                        public void apply(XmlPullParser parser, int userId)
17204                                throws XmlPullParserException, IOException {
17205                            synchronized (mPackages) {
17206                                mSettings.readDefaultAppsLPw(parser, userId);
17207                            }
17208                        }
17209                    } );
17210        } catch (Exception e) {
17211            if (DEBUG_BACKUP) {
17212                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17213            }
17214        }
17215    }
17216
17217    @Override
17218    public byte[] getIntentFilterVerificationBackup(int userId) {
17219        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17220            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17221        }
17222
17223        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17224        try {
17225            final XmlSerializer serializer = new FastXmlSerializer();
17226            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17227            serializer.startDocument(null, true);
17228            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17229
17230            synchronized (mPackages) {
17231                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17232            }
17233
17234            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17235            serializer.endDocument();
17236            serializer.flush();
17237        } catch (Exception e) {
17238            if (DEBUG_BACKUP) {
17239                Slog.e(TAG, "Unable to write default apps for backup", e);
17240            }
17241            return null;
17242        }
17243
17244        return dataStream.toByteArray();
17245    }
17246
17247    @Override
17248    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17249        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17250            throw new SecurityException("Only the system may call restorePreferredActivities()");
17251        }
17252
17253        try {
17254            final XmlPullParser parser = Xml.newPullParser();
17255            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17256            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17257                    new BlobXmlRestorer() {
17258                        @Override
17259                        public void apply(XmlPullParser parser, int userId)
17260                                throws XmlPullParserException, IOException {
17261                            synchronized (mPackages) {
17262                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17263                                mSettings.writeLPr();
17264                            }
17265                        }
17266                    } );
17267        } catch (Exception e) {
17268            if (DEBUG_BACKUP) {
17269                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17270            }
17271        }
17272    }
17273
17274    @Override
17275    public byte[] getPermissionGrantBackup(int userId) {
17276        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17277            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17278        }
17279
17280        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17281        try {
17282            final XmlSerializer serializer = new FastXmlSerializer();
17283            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17284            serializer.startDocument(null, true);
17285            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17286
17287            synchronized (mPackages) {
17288                serializeRuntimePermissionGrantsLPr(serializer, userId);
17289            }
17290
17291            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17292            serializer.endDocument();
17293            serializer.flush();
17294        } catch (Exception e) {
17295            if (DEBUG_BACKUP) {
17296                Slog.e(TAG, "Unable to write default apps for backup", e);
17297            }
17298            return null;
17299        }
17300
17301        return dataStream.toByteArray();
17302    }
17303
17304    @Override
17305    public void restorePermissionGrants(byte[] backup, int userId) {
17306        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17307            throw new SecurityException("Only the system may call restorePermissionGrants()");
17308        }
17309
17310        try {
17311            final XmlPullParser parser = Xml.newPullParser();
17312            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17313            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17314                    new BlobXmlRestorer() {
17315                        @Override
17316                        public void apply(XmlPullParser parser, int userId)
17317                                throws XmlPullParserException, IOException {
17318                            synchronized (mPackages) {
17319                                processRestoredPermissionGrantsLPr(parser, userId);
17320                            }
17321                        }
17322                    } );
17323        } catch (Exception e) {
17324            if (DEBUG_BACKUP) {
17325                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17326            }
17327        }
17328    }
17329
17330    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17331            throws IOException {
17332        serializer.startTag(null, TAG_ALL_GRANTS);
17333
17334        final int N = mSettings.mPackages.size();
17335        for (int i = 0; i < N; i++) {
17336            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17337            boolean pkgGrantsKnown = false;
17338
17339            PermissionsState packagePerms = ps.getPermissionsState();
17340
17341            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17342                final int grantFlags = state.getFlags();
17343                // only look at grants that are not system/policy fixed
17344                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17345                    final boolean isGranted = state.isGranted();
17346                    // And only back up the user-twiddled state bits
17347                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17348                        final String packageName = mSettings.mPackages.keyAt(i);
17349                        if (!pkgGrantsKnown) {
17350                            serializer.startTag(null, TAG_GRANT);
17351                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17352                            pkgGrantsKnown = true;
17353                        }
17354
17355                        final boolean userSet =
17356                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17357                        final boolean userFixed =
17358                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17359                        final boolean revoke =
17360                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17361
17362                        serializer.startTag(null, TAG_PERMISSION);
17363                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17364                        if (isGranted) {
17365                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17366                        }
17367                        if (userSet) {
17368                            serializer.attribute(null, ATTR_USER_SET, "true");
17369                        }
17370                        if (userFixed) {
17371                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17372                        }
17373                        if (revoke) {
17374                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17375                        }
17376                        serializer.endTag(null, TAG_PERMISSION);
17377                    }
17378                }
17379            }
17380
17381            if (pkgGrantsKnown) {
17382                serializer.endTag(null, TAG_GRANT);
17383            }
17384        }
17385
17386        serializer.endTag(null, TAG_ALL_GRANTS);
17387    }
17388
17389    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17390            throws XmlPullParserException, IOException {
17391        String pkgName = null;
17392        int outerDepth = parser.getDepth();
17393        int type;
17394        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17395                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17396            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17397                continue;
17398            }
17399
17400            final String tagName = parser.getName();
17401            if (tagName.equals(TAG_GRANT)) {
17402                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17403                if (DEBUG_BACKUP) {
17404                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17405                }
17406            } else if (tagName.equals(TAG_PERMISSION)) {
17407
17408                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17409                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17410
17411                int newFlagSet = 0;
17412                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17413                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17414                }
17415                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17416                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17417                }
17418                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17419                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17420                }
17421                if (DEBUG_BACKUP) {
17422                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17423                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17424                }
17425                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17426                if (ps != null) {
17427                    // Already installed so we apply the grant immediately
17428                    if (DEBUG_BACKUP) {
17429                        Slog.v(TAG, "        + already installed; applying");
17430                    }
17431                    PermissionsState perms = ps.getPermissionsState();
17432                    BasePermission bp = mSettings.mPermissions.get(permName);
17433                    if (bp != null) {
17434                        if (isGranted) {
17435                            perms.grantRuntimePermission(bp, userId);
17436                        }
17437                        if (newFlagSet != 0) {
17438                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17439                        }
17440                    }
17441                } else {
17442                    // Need to wait for post-restore install to apply the grant
17443                    if (DEBUG_BACKUP) {
17444                        Slog.v(TAG, "        - not yet installed; saving for later");
17445                    }
17446                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17447                            isGranted, newFlagSet, userId);
17448                }
17449            } else {
17450                PackageManagerService.reportSettingsProblem(Log.WARN,
17451                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17452                XmlUtils.skipCurrentTag(parser);
17453            }
17454        }
17455
17456        scheduleWriteSettingsLocked();
17457        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17458    }
17459
17460    @Override
17461    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17462            int sourceUserId, int targetUserId, int flags) {
17463        mContext.enforceCallingOrSelfPermission(
17464                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17465        int callingUid = Binder.getCallingUid();
17466        enforceOwnerRights(ownerPackage, callingUid);
17467        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17468        if (intentFilter.countActions() == 0) {
17469            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17470            return;
17471        }
17472        synchronized (mPackages) {
17473            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17474                    ownerPackage, targetUserId, flags);
17475            CrossProfileIntentResolver resolver =
17476                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17477            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17478            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17479            if (existing != null) {
17480                int size = existing.size();
17481                for (int i = 0; i < size; i++) {
17482                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17483                        return;
17484                    }
17485                }
17486            }
17487            resolver.addFilter(newFilter);
17488            scheduleWritePackageRestrictionsLocked(sourceUserId);
17489        }
17490    }
17491
17492    @Override
17493    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17494        mContext.enforceCallingOrSelfPermission(
17495                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17496        int callingUid = Binder.getCallingUid();
17497        enforceOwnerRights(ownerPackage, callingUid);
17498        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17499        synchronized (mPackages) {
17500            CrossProfileIntentResolver resolver =
17501                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17502            ArraySet<CrossProfileIntentFilter> set =
17503                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17504            for (CrossProfileIntentFilter filter : set) {
17505                if (filter.getOwnerPackage().equals(ownerPackage)) {
17506                    resolver.removeFilter(filter);
17507                }
17508            }
17509            scheduleWritePackageRestrictionsLocked(sourceUserId);
17510        }
17511    }
17512
17513    // Enforcing that callingUid is owning pkg on userId
17514    private void enforceOwnerRights(String pkg, int callingUid) {
17515        // The system owns everything.
17516        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17517            return;
17518        }
17519        int callingUserId = UserHandle.getUserId(callingUid);
17520        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17521        if (pi == null) {
17522            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17523                    + callingUserId);
17524        }
17525        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17526            throw new SecurityException("Calling uid " + callingUid
17527                    + " does not own package " + pkg);
17528        }
17529    }
17530
17531    @Override
17532    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17533        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17534    }
17535
17536    private Intent getHomeIntent() {
17537        Intent intent = new Intent(Intent.ACTION_MAIN);
17538        intent.addCategory(Intent.CATEGORY_HOME);
17539        intent.addCategory(Intent.CATEGORY_DEFAULT);
17540        return intent;
17541    }
17542
17543    private IntentFilter getHomeFilter() {
17544        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17545        filter.addCategory(Intent.CATEGORY_HOME);
17546        filter.addCategory(Intent.CATEGORY_DEFAULT);
17547        return filter;
17548    }
17549
17550    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17551            int userId) {
17552        Intent intent  = getHomeIntent();
17553        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17554                PackageManager.GET_META_DATA, userId);
17555        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17556                true, false, false, userId);
17557
17558        allHomeCandidates.clear();
17559        if (list != null) {
17560            for (ResolveInfo ri : list) {
17561                allHomeCandidates.add(ri);
17562            }
17563        }
17564        return (preferred == null || preferred.activityInfo == null)
17565                ? null
17566                : new ComponentName(preferred.activityInfo.packageName,
17567                        preferred.activityInfo.name);
17568    }
17569
17570    @Override
17571    public void setHomeActivity(ComponentName comp, int userId) {
17572        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17573        getHomeActivitiesAsUser(homeActivities, userId);
17574
17575        boolean found = false;
17576
17577        final int size = homeActivities.size();
17578        final ComponentName[] set = new ComponentName[size];
17579        for (int i = 0; i < size; i++) {
17580            final ResolveInfo candidate = homeActivities.get(i);
17581            final ActivityInfo info = candidate.activityInfo;
17582            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17583            set[i] = activityName;
17584            if (!found && activityName.equals(comp)) {
17585                found = true;
17586            }
17587        }
17588        if (!found) {
17589            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17590                    + userId);
17591        }
17592        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17593                set, comp, userId);
17594    }
17595
17596    private @Nullable String getSetupWizardPackageName() {
17597        final Intent intent = new Intent(Intent.ACTION_MAIN);
17598        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17599
17600        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17601                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17602                        | MATCH_DISABLED_COMPONENTS,
17603                UserHandle.myUserId());
17604        if (matches.size() == 1) {
17605            return matches.get(0).getComponentInfo().packageName;
17606        } else {
17607            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17608                    + ": matches=" + matches);
17609            return null;
17610        }
17611    }
17612
17613    @Override
17614    public void setApplicationEnabledSetting(String appPackageName,
17615            int newState, int flags, int userId, String callingPackage) {
17616        if (!sUserManager.exists(userId)) return;
17617        if (callingPackage == null) {
17618            callingPackage = Integer.toString(Binder.getCallingUid());
17619        }
17620        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17621    }
17622
17623    @Override
17624    public void setComponentEnabledSetting(ComponentName componentName,
17625            int newState, int flags, int userId) {
17626        if (!sUserManager.exists(userId)) return;
17627        setEnabledSetting(componentName.getPackageName(),
17628                componentName.getClassName(), newState, flags, userId, null);
17629    }
17630
17631    private void setEnabledSetting(final String packageName, String className, int newState,
17632            final int flags, int userId, String callingPackage) {
17633        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17634              || newState == COMPONENT_ENABLED_STATE_ENABLED
17635              || newState == COMPONENT_ENABLED_STATE_DISABLED
17636              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17637              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17638            throw new IllegalArgumentException("Invalid new component state: "
17639                    + newState);
17640        }
17641        PackageSetting pkgSetting;
17642        final int uid = Binder.getCallingUid();
17643        final int permission;
17644        if (uid == Process.SYSTEM_UID) {
17645            permission = PackageManager.PERMISSION_GRANTED;
17646        } else {
17647            permission = mContext.checkCallingOrSelfPermission(
17648                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17649        }
17650        enforceCrossUserPermission(uid, userId,
17651                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17652        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17653        boolean sendNow = false;
17654        boolean isApp = (className == null);
17655        String componentName = isApp ? packageName : className;
17656        int packageUid = -1;
17657        ArrayList<String> components;
17658
17659        // writer
17660        synchronized (mPackages) {
17661            pkgSetting = mSettings.mPackages.get(packageName);
17662            if (pkgSetting == null) {
17663                if (className == null) {
17664                    throw new IllegalArgumentException("Unknown package: " + packageName);
17665                }
17666                throw new IllegalArgumentException(
17667                        "Unknown component: " + packageName + "/" + className);
17668            }
17669        }
17670
17671        // Limit who can change which apps
17672        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17673            // Don't allow apps that don't have permission to modify other apps
17674            if (!allowedByPermission) {
17675                throw new SecurityException(
17676                        "Permission Denial: attempt to change component state from pid="
17677                        + Binder.getCallingPid()
17678                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17679            }
17680            // Don't allow changing protected packages.
17681            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
17682                throw new SecurityException("Cannot disable a protected package: " + packageName);
17683            }
17684        }
17685
17686        synchronized (mPackages) {
17687            if (uid == Process.SHELL_UID) {
17688                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17689                int oldState = pkgSetting.getEnabled(userId);
17690                if (className == null
17691                    &&
17692                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17693                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17694                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17695                    &&
17696                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17697                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17698                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17699                    // ok
17700                } else {
17701                    throw new SecurityException(
17702                            "Shell cannot change component state for " + packageName + "/"
17703                            + className + " to " + newState);
17704                }
17705            }
17706            if (className == null) {
17707                // We're dealing with an application/package level state change
17708                if (pkgSetting.getEnabled(userId) == newState) {
17709                    // Nothing to do
17710                    return;
17711                }
17712                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17713                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17714                    // Don't care about who enables an app.
17715                    callingPackage = null;
17716                }
17717                pkgSetting.setEnabled(newState, userId, callingPackage);
17718                // pkgSetting.pkg.mSetEnabled = newState;
17719            } else {
17720                // We're dealing with a component level state change
17721                // First, verify that this is a valid class name.
17722                PackageParser.Package pkg = pkgSetting.pkg;
17723                if (pkg == null || !pkg.hasComponentClassName(className)) {
17724                    if (pkg != null &&
17725                            pkg.applicationInfo.targetSdkVersion >=
17726                                    Build.VERSION_CODES.JELLY_BEAN) {
17727                        throw new IllegalArgumentException("Component class " + className
17728                                + " does not exist in " + packageName);
17729                    } else {
17730                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17731                                + className + " does not exist in " + packageName);
17732                    }
17733                }
17734                switch (newState) {
17735                case COMPONENT_ENABLED_STATE_ENABLED:
17736                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17737                        return;
17738                    }
17739                    break;
17740                case COMPONENT_ENABLED_STATE_DISABLED:
17741                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17742                        return;
17743                    }
17744                    break;
17745                case COMPONENT_ENABLED_STATE_DEFAULT:
17746                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17747                        return;
17748                    }
17749                    break;
17750                default:
17751                    Slog.e(TAG, "Invalid new component state: " + newState);
17752                    return;
17753                }
17754            }
17755            scheduleWritePackageRestrictionsLocked(userId);
17756            components = mPendingBroadcasts.get(userId, packageName);
17757            final boolean newPackage = components == null;
17758            if (newPackage) {
17759                components = new ArrayList<String>();
17760            }
17761            if (!components.contains(componentName)) {
17762                components.add(componentName);
17763            }
17764            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17765                sendNow = true;
17766                // Purge entry from pending broadcast list if another one exists already
17767                // since we are sending one right away.
17768                mPendingBroadcasts.remove(userId, packageName);
17769            } else {
17770                if (newPackage) {
17771                    mPendingBroadcasts.put(userId, packageName, components);
17772                }
17773                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17774                    // Schedule a message
17775                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17776                }
17777            }
17778        }
17779
17780        long callingId = Binder.clearCallingIdentity();
17781        try {
17782            if (sendNow) {
17783                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17784                sendPackageChangedBroadcast(packageName,
17785                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17786            }
17787        } finally {
17788            Binder.restoreCallingIdentity(callingId);
17789        }
17790    }
17791
17792    @Override
17793    public void flushPackageRestrictionsAsUser(int userId) {
17794        if (!sUserManager.exists(userId)) {
17795            return;
17796        }
17797        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17798                false /* checkShell */, "flushPackageRestrictions");
17799        synchronized (mPackages) {
17800            mSettings.writePackageRestrictionsLPr(userId);
17801            mDirtyUsers.remove(userId);
17802            if (mDirtyUsers.isEmpty()) {
17803                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17804            }
17805        }
17806    }
17807
17808    private void sendPackageChangedBroadcast(String packageName,
17809            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17810        if (DEBUG_INSTALL)
17811            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17812                    + componentNames);
17813        Bundle extras = new Bundle(4);
17814        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17815        String nameList[] = new String[componentNames.size()];
17816        componentNames.toArray(nameList);
17817        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17818        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17819        extras.putInt(Intent.EXTRA_UID, packageUid);
17820        // If this is not reporting a change of the overall package, then only send it
17821        // to registered receivers.  We don't want to launch a swath of apps for every
17822        // little component state change.
17823        final int flags = !componentNames.contains(packageName)
17824                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17825        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17826                new int[] {UserHandle.getUserId(packageUid)});
17827    }
17828
17829    @Override
17830    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17831        if (!sUserManager.exists(userId)) return;
17832        final int uid = Binder.getCallingUid();
17833        final int permission = mContext.checkCallingOrSelfPermission(
17834                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17835        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17836        enforceCrossUserPermission(uid, userId,
17837                true /* requireFullPermission */, true /* checkShell */, "stop package");
17838        // writer
17839        synchronized (mPackages) {
17840            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17841                    allowedByPermission, uid, userId)) {
17842                scheduleWritePackageRestrictionsLocked(userId);
17843            }
17844        }
17845    }
17846
17847    @Override
17848    public String getInstallerPackageName(String packageName) {
17849        // reader
17850        synchronized (mPackages) {
17851            return mSettings.getInstallerPackageNameLPr(packageName);
17852        }
17853    }
17854
17855    public boolean isOrphaned(String packageName) {
17856        // reader
17857        synchronized (mPackages) {
17858            return mSettings.isOrphaned(packageName);
17859        }
17860    }
17861
17862    @Override
17863    public int getApplicationEnabledSetting(String packageName, int userId) {
17864        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17865        int uid = Binder.getCallingUid();
17866        enforceCrossUserPermission(uid, userId,
17867                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17868        // reader
17869        synchronized (mPackages) {
17870            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17871        }
17872    }
17873
17874    @Override
17875    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17876        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17877        int uid = Binder.getCallingUid();
17878        enforceCrossUserPermission(uid, userId,
17879                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17880        // reader
17881        synchronized (mPackages) {
17882            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17883        }
17884    }
17885
17886    @Override
17887    public void enterSafeMode() {
17888        enforceSystemOrRoot("Only the system can request entering safe mode");
17889
17890        if (!mSystemReady) {
17891            mSafeMode = true;
17892        }
17893    }
17894
17895    @Override
17896    public void systemReady() {
17897        mSystemReady = true;
17898
17899        // Read the compatibilty setting when the system is ready.
17900        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17901                mContext.getContentResolver(),
17902                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17903        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17904        if (DEBUG_SETTINGS) {
17905            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17906        }
17907
17908        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17909
17910        synchronized (mPackages) {
17911            // Verify that all of the preferred activity components actually
17912            // exist.  It is possible for applications to be updated and at
17913            // that point remove a previously declared activity component that
17914            // had been set as a preferred activity.  We try to clean this up
17915            // the next time we encounter that preferred activity, but it is
17916            // possible for the user flow to never be able to return to that
17917            // situation so here we do a sanity check to make sure we haven't
17918            // left any junk around.
17919            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17920            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17921                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17922                removed.clear();
17923                for (PreferredActivity pa : pir.filterSet()) {
17924                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17925                        removed.add(pa);
17926                    }
17927                }
17928                if (removed.size() > 0) {
17929                    for (int r=0; r<removed.size(); r++) {
17930                        PreferredActivity pa = removed.get(r);
17931                        Slog.w(TAG, "Removing dangling preferred activity: "
17932                                + pa.mPref.mComponent);
17933                        pir.removeFilter(pa);
17934                    }
17935                    mSettings.writePackageRestrictionsLPr(
17936                            mSettings.mPreferredActivities.keyAt(i));
17937                }
17938            }
17939
17940            for (int userId : UserManagerService.getInstance().getUserIds()) {
17941                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17942                    grantPermissionsUserIds = ArrayUtils.appendInt(
17943                            grantPermissionsUserIds, userId);
17944                }
17945            }
17946        }
17947        sUserManager.systemReady();
17948
17949        // If we upgraded grant all default permissions before kicking off.
17950        for (int userId : grantPermissionsUserIds) {
17951            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17952        }
17953
17954        // Kick off any messages waiting for system ready
17955        if (mPostSystemReadyMessages != null) {
17956            for (Message msg : mPostSystemReadyMessages) {
17957                msg.sendToTarget();
17958            }
17959            mPostSystemReadyMessages = null;
17960        }
17961
17962        // Watch for external volumes that come and go over time
17963        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17964        storage.registerListener(mStorageListener);
17965
17966        mInstallerService.systemReady();
17967        mPackageDexOptimizer.systemReady();
17968
17969        MountServiceInternal mountServiceInternal = LocalServices.getService(
17970                MountServiceInternal.class);
17971        mountServiceInternal.addExternalStoragePolicy(
17972                new MountServiceInternal.ExternalStorageMountPolicy() {
17973            @Override
17974            public int getMountMode(int uid, String packageName) {
17975                if (Process.isIsolated(uid)) {
17976                    return Zygote.MOUNT_EXTERNAL_NONE;
17977                }
17978                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17979                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17980                }
17981                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17982                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17983                }
17984                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17985                    return Zygote.MOUNT_EXTERNAL_READ;
17986                }
17987                return Zygote.MOUNT_EXTERNAL_WRITE;
17988            }
17989
17990            @Override
17991            public boolean hasExternalStorage(int uid, String packageName) {
17992                return true;
17993            }
17994        });
17995
17996        // Now that we're mostly running, clean up stale users and apps
17997        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
17998        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
17999    }
18000
18001    @Override
18002    public boolean isSafeMode() {
18003        return mSafeMode;
18004    }
18005
18006    @Override
18007    public boolean hasSystemUidErrors() {
18008        return mHasSystemUidErrors;
18009    }
18010
18011    static String arrayToString(int[] array) {
18012        StringBuffer buf = new StringBuffer(128);
18013        buf.append('[');
18014        if (array != null) {
18015            for (int i=0; i<array.length; i++) {
18016                if (i > 0) buf.append(", ");
18017                buf.append(array[i]);
18018            }
18019        }
18020        buf.append(']');
18021        return buf.toString();
18022    }
18023
18024    static class DumpState {
18025        public static final int DUMP_LIBS = 1 << 0;
18026        public static final int DUMP_FEATURES = 1 << 1;
18027        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18028        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18029        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18030        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18031        public static final int DUMP_PERMISSIONS = 1 << 6;
18032        public static final int DUMP_PACKAGES = 1 << 7;
18033        public static final int DUMP_SHARED_USERS = 1 << 8;
18034        public static final int DUMP_MESSAGES = 1 << 9;
18035        public static final int DUMP_PROVIDERS = 1 << 10;
18036        public static final int DUMP_VERIFIERS = 1 << 11;
18037        public static final int DUMP_PREFERRED = 1 << 12;
18038        public static final int DUMP_PREFERRED_XML = 1 << 13;
18039        public static final int DUMP_KEYSETS = 1 << 14;
18040        public static final int DUMP_VERSION = 1 << 15;
18041        public static final int DUMP_INSTALLS = 1 << 16;
18042        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18043        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18044        public static final int DUMP_FROZEN = 1 << 19;
18045        public static final int DUMP_DEXOPT = 1 << 20;
18046        public static final int DUMP_COMPILER_STATS = 1 << 21;
18047
18048        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18049
18050        private int mTypes;
18051
18052        private int mOptions;
18053
18054        private boolean mTitlePrinted;
18055
18056        private SharedUserSetting mSharedUser;
18057
18058        public boolean isDumping(int type) {
18059            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18060                return true;
18061            }
18062
18063            return (mTypes & type) != 0;
18064        }
18065
18066        public void setDump(int type) {
18067            mTypes |= type;
18068        }
18069
18070        public boolean isOptionEnabled(int option) {
18071            return (mOptions & option) != 0;
18072        }
18073
18074        public void setOptionEnabled(int option) {
18075            mOptions |= option;
18076        }
18077
18078        public boolean onTitlePrinted() {
18079            final boolean printed = mTitlePrinted;
18080            mTitlePrinted = true;
18081            return printed;
18082        }
18083
18084        public boolean getTitlePrinted() {
18085            return mTitlePrinted;
18086        }
18087
18088        public void setTitlePrinted(boolean enabled) {
18089            mTitlePrinted = enabled;
18090        }
18091
18092        public SharedUserSetting getSharedUser() {
18093            return mSharedUser;
18094        }
18095
18096        public void setSharedUser(SharedUserSetting user) {
18097            mSharedUser = user;
18098        }
18099    }
18100
18101    @Override
18102    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18103            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18104        (new PackageManagerShellCommand(this)).exec(
18105                this, in, out, err, args, resultReceiver);
18106    }
18107
18108    @Override
18109    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18110        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18111                != PackageManager.PERMISSION_GRANTED) {
18112            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18113                    + Binder.getCallingPid()
18114                    + ", uid=" + Binder.getCallingUid()
18115                    + " without permission "
18116                    + android.Manifest.permission.DUMP);
18117            return;
18118        }
18119
18120        DumpState dumpState = new DumpState();
18121        boolean fullPreferred = false;
18122        boolean checkin = false;
18123
18124        String packageName = null;
18125        ArraySet<String> permissionNames = null;
18126
18127        int opti = 0;
18128        while (opti < args.length) {
18129            String opt = args[opti];
18130            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18131                break;
18132            }
18133            opti++;
18134
18135            if ("-a".equals(opt)) {
18136                // Right now we only know how to print all.
18137            } else if ("-h".equals(opt)) {
18138                pw.println("Package manager dump options:");
18139                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18140                pw.println("    --checkin: dump for a checkin");
18141                pw.println("    -f: print details of intent filters");
18142                pw.println("    -h: print this help");
18143                pw.println("  cmd may be one of:");
18144                pw.println("    l[ibraries]: list known shared libraries");
18145                pw.println("    f[eatures]: list device features");
18146                pw.println("    k[eysets]: print known keysets");
18147                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18148                pw.println("    perm[issions]: dump permissions");
18149                pw.println("    permission [name ...]: dump declaration and use of given permission");
18150                pw.println("    pref[erred]: print preferred package settings");
18151                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18152                pw.println("    prov[iders]: dump content providers");
18153                pw.println("    p[ackages]: dump installed packages");
18154                pw.println("    s[hared-users]: dump shared user IDs");
18155                pw.println("    m[essages]: print collected runtime messages");
18156                pw.println("    v[erifiers]: print package verifier info");
18157                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18158                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18159                pw.println("    version: print database version info");
18160                pw.println("    write: write current settings now");
18161                pw.println("    installs: details about install sessions");
18162                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18163                pw.println("    dexopt: dump dexopt state");
18164                pw.println("    compiler-stats: dump compiler statistics");
18165                pw.println("    <package.name>: info about given package");
18166                return;
18167            } else if ("--checkin".equals(opt)) {
18168                checkin = true;
18169            } else if ("-f".equals(opt)) {
18170                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18171            } else {
18172                pw.println("Unknown argument: " + opt + "; use -h for help");
18173            }
18174        }
18175
18176        // Is the caller requesting to dump a particular piece of data?
18177        if (opti < args.length) {
18178            String cmd = args[opti];
18179            opti++;
18180            // Is this a package name?
18181            if ("android".equals(cmd) || cmd.contains(".")) {
18182                packageName = cmd;
18183                // When dumping a single package, we always dump all of its
18184                // filter information since the amount of data will be reasonable.
18185                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18186            } else if ("check-permission".equals(cmd)) {
18187                if (opti >= args.length) {
18188                    pw.println("Error: check-permission missing permission argument");
18189                    return;
18190                }
18191                String perm = args[opti];
18192                opti++;
18193                if (opti >= args.length) {
18194                    pw.println("Error: check-permission missing package argument");
18195                    return;
18196                }
18197                String pkg = args[opti];
18198                opti++;
18199                int user = UserHandle.getUserId(Binder.getCallingUid());
18200                if (opti < args.length) {
18201                    try {
18202                        user = Integer.parseInt(args[opti]);
18203                    } catch (NumberFormatException e) {
18204                        pw.println("Error: check-permission user argument is not a number: "
18205                                + args[opti]);
18206                        return;
18207                    }
18208                }
18209                pw.println(checkPermission(perm, pkg, user));
18210                return;
18211            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18212                dumpState.setDump(DumpState.DUMP_LIBS);
18213            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18214                dumpState.setDump(DumpState.DUMP_FEATURES);
18215            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18216                if (opti >= args.length) {
18217                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18218                            | DumpState.DUMP_SERVICE_RESOLVERS
18219                            | DumpState.DUMP_RECEIVER_RESOLVERS
18220                            | DumpState.DUMP_CONTENT_RESOLVERS);
18221                } else {
18222                    while (opti < args.length) {
18223                        String name = args[opti];
18224                        if ("a".equals(name) || "activity".equals(name)) {
18225                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18226                        } else if ("s".equals(name) || "service".equals(name)) {
18227                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18228                        } else if ("r".equals(name) || "receiver".equals(name)) {
18229                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18230                        } else if ("c".equals(name) || "content".equals(name)) {
18231                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18232                        } else {
18233                            pw.println("Error: unknown resolver table type: " + name);
18234                            return;
18235                        }
18236                        opti++;
18237                    }
18238                }
18239            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18240                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18241            } else if ("permission".equals(cmd)) {
18242                if (opti >= args.length) {
18243                    pw.println("Error: permission requires permission name");
18244                    return;
18245                }
18246                permissionNames = new ArraySet<>();
18247                while (opti < args.length) {
18248                    permissionNames.add(args[opti]);
18249                    opti++;
18250                }
18251                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18252                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18253            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18254                dumpState.setDump(DumpState.DUMP_PREFERRED);
18255            } else if ("preferred-xml".equals(cmd)) {
18256                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18257                if (opti < args.length && "--full".equals(args[opti])) {
18258                    fullPreferred = true;
18259                    opti++;
18260                }
18261            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18262                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18263            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18264                dumpState.setDump(DumpState.DUMP_PACKAGES);
18265            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18266                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18267            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18268                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18269            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18270                dumpState.setDump(DumpState.DUMP_MESSAGES);
18271            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18272                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18273            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18274                    || "intent-filter-verifiers".equals(cmd)) {
18275                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18276            } else if ("version".equals(cmd)) {
18277                dumpState.setDump(DumpState.DUMP_VERSION);
18278            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18279                dumpState.setDump(DumpState.DUMP_KEYSETS);
18280            } else if ("installs".equals(cmd)) {
18281                dumpState.setDump(DumpState.DUMP_INSTALLS);
18282            } else if ("frozen".equals(cmd)) {
18283                dumpState.setDump(DumpState.DUMP_FROZEN);
18284            } else if ("dexopt".equals(cmd)) {
18285                dumpState.setDump(DumpState.DUMP_DEXOPT);
18286            } else if ("compiler-stats".equals(cmd)) {
18287                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
18288            } else if ("write".equals(cmd)) {
18289                synchronized (mPackages) {
18290                    mSettings.writeLPr();
18291                    pw.println("Settings written.");
18292                    return;
18293                }
18294            }
18295        }
18296
18297        if (checkin) {
18298            pw.println("vers,1");
18299        }
18300
18301        // reader
18302        synchronized (mPackages) {
18303            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18304                if (!checkin) {
18305                    if (dumpState.onTitlePrinted())
18306                        pw.println();
18307                    pw.println("Database versions:");
18308                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18309                }
18310            }
18311
18312            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18313                if (!checkin) {
18314                    if (dumpState.onTitlePrinted())
18315                        pw.println();
18316                    pw.println("Verifiers:");
18317                    pw.print("  Required: ");
18318                    pw.print(mRequiredVerifierPackage);
18319                    pw.print(" (uid=");
18320                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18321                            UserHandle.USER_SYSTEM));
18322                    pw.println(")");
18323                } else if (mRequiredVerifierPackage != null) {
18324                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18325                    pw.print(",");
18326                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18327                            UserHandle.USER_SYSTEM));
18328                }
18329            }
18330
18331            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18332                    packageName == null) {
18333                if (mIntentFilterVerifierComponent != null) {
18334                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18335                    if (!checkin) {
18336                        if (dumpState.onTitlePrinted())
18337                            pw.println();
18338                        pw.println("Intent Filter Verifier:");
18339                        pw.print("  Using: ");
18340                        pw.print(verifierPackageName);
18341                        pw.print(" (uid=");
18342                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18343                                UserHandle.USER_SYSTEM));
18344                        pw.println(")");
18345                    } else if (verifierPackageName != null) {
18346                        pw.print("ifv,"); pw.print(verifierPackageName);
18347                        pw.print(",");
18348                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18349                                UserHandle.USER_SYSTEM));
18350                    }
18351                } else {
18352                    pw.println();
18353                    pw.println("No Intent Filter Verifier available!");
18354                }
18355            }
18356
18357            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18358                boolean printedHeader = false;
18359                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18360                while (it.hasNext()) {
18361                    String name = it.next();
18362                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18363                    if (!checkin) {
18364                        if (!printedHeader) {
18365                            if (dumpState.onTitlePrinted())
18366                                pw.println();
18367                            pw.println("Libraries:");
18368                            printedHeader = true;
18369                        }
18370                        pw.print("  ");
18371                    } else {
18372                        pw.print("lib,");
18373                    }
18374                    pw.print(name);
18375                    if (!checkin) {
18376                        pw.print(" -> ");
18377                    }
18378                    if (ent.path != null) {
18379                        if (!checkin) {
18380                            pw.print("(jar) ");
18381                            pw.print(ent.path);
18382                        } else {
18383                            pw.print(",jar,");
18384                            pw.print(ent.path);
18385                        }
18386                    } else {
18387                        if (!checkin) {
18388                            pw.print("(apk) ");
18389                            pw.print(ent.apk);
18390                        } else {
18391                            pw.print(",apk,");
18392                            pw.print(ent.apk);
18393                        }
18394                    }
18395                    pw.println();
18396                }
18397            }
18398
18399            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18400                if (dumpState.onTitlePrinted())
18401                    pw.println();
18402                if (!checkin) {
18403                    pw.println("Features:");
18404                }
18405
18406                for (FeatureInfo feat : mAvailableFeatures.values()) {
18407                    if (checkin) {
18408                        pw.print("feat,");
18409                        pw.print(feat.name);
18410                        pw.print(",");
18411                        pw.println(feat.version);
18412                    } else {
18413                        pw.print("  ");
18414                        pw.print(feat.name);
18415                        if (feat.version > 0) {
18416                            pw.print(" version=");
18417                            pw.print(feat.version);
18418                        }
18419                        pw.println();
18420                    }
18421                }
18422            }
18423
18424            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18425                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18426                        : "Activity Resolver Table:", "  ", packageName,
18427                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18428                    dumpState.setTitlePrinted(true);
18429                }
18430            }
18431            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18432                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18433                        : "Receiver Resolver Table:", "  ", packageName,
18434                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18435                    dumpState.setTitlePrinted(true);
18436                }
18437            }
18438            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18439                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18440                        : "Service Resolver Table:", "  ", packageName,
18441                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18442                    dumpState.setTitlePrinted(true);
18443                }
18444            }
18445            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18446                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18447                        : "Provider Resolver Table:", "  ", packageName,
18448                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18449                    dumpState.setTitlePrinted(true);
18450                }
18451            }
18452
18453            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18454                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18455                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18456                    int user = mSettings.mPreferredActivities.keyAt(i);
18457                    if (pir.dump(pw,
18458                            dumpState.getTitlePrinted()
18459                                ? "\nPreferred Activities User " + user + ":"
18460                                : "Preferred Activities User " + user + ":", "  ",
18461                            packageName, true, false)) {
18462                        dumpState.setTitlePrinted(true);
18463                    }
18464                }
18465            }
18466
18467            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18468                pw.flush();
18469                FileOutputStream fout = new FileOutputStream(fd);
18470                BufferedOutputStream str = new BufferedOutputStream(fout);
18471                XmlSerializer serializer = new FastXmlSerializer();
18472                try {
18473                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18474                    serializer.startDocument(null, true);
18475                    serializer.setFeature(
18476                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18477                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18478                    serializer.endDocument();
18479                    serializer.flush();
18480                } catch (IllegalArgumentException e) {
18481                    pw.println("Failed writing: " + e);
18482                } catch (IllegalStateException e) {
18483                    pw.println("Failed writing: " + e);
18484                } catch (IOException e) {
18485                    pw.println("Failed writing: " + e);
18486                }
18487            }
18488
18489            if (!checkin
18490                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18491                    && packageName == null) {
18492                pw.println();
18493                int count = mSettings.mPackages.size();
18494                if (count == 0) {
18495                    pw.println("No applications!");
18496                    pw.println();
18497                } else {
18498                    final String prefix = "  ";
18499                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18500                    if (allPackageSettings.size() == 0) {
18501                        pw.println("No domain preferred apps!");
18502                        pw.println();
18503                    } else {
18504                        pw.println("App verification status:");
18505                        pw.println();
18506                        count = 0;
18507                        for (PackageSetting ps : allPackageSettings) {
18508                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18509                            if (ivi == null || ivi.getPackageName() == null) continue;
18510                            pw.println(prefix + "Package: " + ivi.getPackageName());
18511                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18512                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18513                            pw.println();
18514                            count++;
18515                        }
18516                        if (count == 0) {
18517                            pw.println(prefix + "No app verification established.");
18518                            pw.println();
18519                        }
18520                        for (int userId : sUserManager.getUserIds()) {
18521                            pw.println("App linkages for user " + userId + ":");
18522                            pw.println();
18523                            count = 0;
18524                            for (PackageSetting ps : allPackageSettings) {
18525                                final long status = ps.getDomainVerificationStatusForUser(userId);
18526                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18527                                    continue;
18528                                }
18529                                pw.println(prefix + "Package: " + ps.name);
18530                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18531                                String statusStr = IntentFilterVerificationInfo.
18532                                        getStatusStringFromValue(status);
18533                                pw.println(prefix + "Status:  " + statusStr);
18534                                pw.println();
18535                                count++;
18536                            }
18537                            if (count == 0) {
18538                                pw.println(prefix + "No configured app linkages.");
18539                                pw.println();
18540                            }
18541                        }
18542                    }
18543                }
18544            }
18545
18546            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18547                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18548                if (packageName == null && permissionNames == null) {
18549                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18550                        if (iperm == 0) {
18551                            if (dumpState.onTitlePrinted())
18552                                pw.println();
18553                            pw.println("AppOp Permissions:");
18554                        }
18555                        pw.print("  AppOp Permission ");
18556                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18557                        pw.println(":");
18558                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18559                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18560                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18561                        }
18562                    }
18563                }
18564            }
18565
18566            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18567                boolean printedSomething = false;
18568                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18569                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18570                        continue;
18571                    }
18572                    if (!printedSomething) {
18573                        if (dumpState.onTitlePrinted())
18574                            pw.println();
18575                        pw.println("Registered ContentProviders:");
18576                        printedSomething = true;
18577                    }
18578                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18579                    pw.print("    "); pw.println(p.toString());
18580                }
18581                printedSomething = false;
18582                for (Map.Entry<String, PackageParser.Provider> entry :
18583                        mProvidersByAuthority.entrySet()) {
18584                    PackageParser.Provider p = entry.getValue();
18585                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18586                        continue;
18587                    }
18588                    if (!printedSomething) {
18589                        if (dumpState.onTitlePrinted())
18590                            pw.println();
18591                        pw.println("ContentProvider Authorities:");
18592                        printedSomething = true;
18593                    }
18594                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18595                    pw.print("    "); pw.println(p.toString());
18596                    if (p.info != null && p.info.applicationInfo != null) {
18597                        final String appInfo = p.info.applicationInfo.toString();
18598                        pw.print("      applicationInfo="); pw.println(appInfo);
18599                    }
18600                }
18601            }
18602
18603            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18604                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18605            }
18606
18607            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18608                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18609            }
18610
18611            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18612                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18613            }
18614
18615            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18616                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18617            }
18618
18619            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18620                // XXX should handle packageName != null by dumping only install data that
18621                // the given package is involved with.
18622                if (dumpState.onTitlePrinted()) pw.println();
18623                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18624            }
18625
18626            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18627                // XXX should handle packageName != null by dumping only install data that
18628                // the given package is involved with.
18629                if (dumpState.onTitlePrinted()) pw.println();
18630
18631                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18632                ipw.println();
18633                ipw.println("Frozen packages:");
18634                ipw.increaseIndent();
18635                if (mFrozenPackages.size() == 0) {
18636                    ipw.println("(none)");
18637                } else {
18638                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18639                        ipw.println(mFrozenPackages.valueAt(i));
18640                    }
18641                }
18642                ipw.decreaseIndent();
18643            }
18644
18645            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18646                if (dumpState.onTitlePrinted()) pw.println();
18647                dumpDexoptStateLPr(pw, packageName);
18648            }
18649
18650            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
18651                if (dumpState.onTitlePrinted()) pw.println();
18652                dumpCompilerStatsLPr(pw, packageName);
18653            }
18654
18655            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18656                if (dumpState.onTitlePrinted()) pw.println();
18657                mSettings.dumpReadMessagesLPr(pw, dumpState);
18658
18659                pw.println();
18660                pw.println("Package warning messages:");
18661                BufferedReader in = null;
18662                String line = null;
18663                try {
18664                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18665                    while ((line = in.readLine()) != null) {
18666                        if (line.contains("ignored: updated version")) continue;
18667                        pw.println(line);
18668                    }
18669                } catch (IOException ignored) {
18670                } finally {
18671                    IoUtils.closeQuietly(in);
18672                }
18673            }
18674
18675            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18676                BufferedReader in = null;
18677                String line = null;
18678                try {
18679                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18680                    while ((line = in.readLine()) != null) {
18681                        if (line.contains("ignored: updated version")) continue;
18682                        pw.print("msg,");
18683                        pw.println(line);
18684                    }
18685                } catch (IOException ignored) {
18686                } finally {
18687                    IoUtils.closeQuietly(in);
18688                }
18689            }
18690        }
18691    }
18692
18693    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18694        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18695        ipw.println();
18696        ipw.println("Dexopt state:");
18697        ipw.increaseIndent();
18698        Collection<PackageParser.Package> packages = null;
18699        if (packageName != null) {
18700            PackageParser.Package targetPackage = mPackages.get(packageName);
18701            if (targetPackage != null) {
18702                packages = Collections.singletonList(targetPackage);
18703            } else {
18704                ipw.println("Unable to find package: " + packageName);
18705                return;
18706            }
18707        } else {
18708            packages = mPackages.values();
18709        }
18710
18711        for (PackageParser.Package pkg : packages) {
18712            ipw.println("[" + pkg.packageName + "]");
18713            ipw.increaseIndent();
18714            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18715            ipw.decreaseIndent();
18716        }
18717    }
18718
18719    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
18720        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18721        ipw.println();
18722        ipw.println("Compiler stats:");
18723        ipw.increaseIndent();
18724        Collection<PackageParser.Package> packages = null;
18725        if (packageName != null) {
18726            PackageParser.Package targetPackage = mPackages.get(packageName);
18727            if (targetPackage != null) {
18728                packages = Collections.singletonList(targetPackage);
18729            } else {
18730                ipw.println("Unable to find package: " + packageName);
18731                return;
18732            }
18733        } else {
18734            packages = mPackages.values();
18735        }
18736
18737        for (PackageParser.Package pkg : packages) {
18738            ipw.println("[" + pkg.packageName + "]");
18739            ipw.increaseIndent();
18740
18741            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
18742            if (stats == null) {
18743                ipw.println("(No recorded stats)");
18744            } else {
18745                stats.dump(ipw);
18746            }
18747            ipw.decreaseIndent();
18748        }
18749    }
18750
18751    private String dumpDomainString(String packageName) {
18752        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18753                .getList();
18754        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18755
18756        ArraySet<String> result = new ArraySet<>();
18757        if (iviList.size() > 0) {
18758            for (IntentFilterVerificationInfo ivi : iviList) {
18759                for (String host : ivi.getDomains()) {
18760                    result.add(host);
18761                }
18762            }
18763        }
18764        if (filters != null && filters.size() > 0) {
18765            for (IntentFilter filter : filters) {
18766                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18767                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18768                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18769                    result.addAll(filter.getHostsList());
18770                }
18771            }
18772        }
18773
18774        StringBuilder sb = new StringBuilder(result.size() * 16);
18775        for (String domain : result) {
18776            if (sb.length() > 0) sb.append(" ");
18777            sb.append(domain);
18778        }
18779        return sb.toString();
18780    }
18781
18782    // ------- apps on sdcard specific code -------
18783    static final boolean DEBUG_SD_INSTALL = false;
18784
18785    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18786
18787    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18788
18789    private boolean mMediaMounted = false;
18790
18791    static String getEncryptKey() {
18792        try {
18793            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18794                    SD_ENCRYPTION_KEYSTORE_NAME);
18795            if (sdEncKey == null) {
18796                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18797                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18798                if (sdEncKey == null) {
18799                    Slog.e(TAG, "Failed to create encryption keys");
18800                    return null;
18801                }
18802            }
18803            return sdEncKey;
18804        } catch (NoSuchAlgorithmException nsae) {
18805            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18806            return null;
18807        } catch (IOException ioe) {
18808            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18809            return null;
18810        }
18811    }
18812
18813    /*
18814     * Update media status on PackageManager.
18815     */
18816    @Override
18817    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18818        int callingUid = Binder.getCallingUid();
18819        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18820            throw new SecurityException("Media status can only be updated by the system");
18821        }
18822        // reader; this apparently protects mMediaMounted, but should probably
18823        // be a different lock in that case.
18824        synchronized (mPackages) {
18825            Log.i(TAG, "Updating external media status from "
18826                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18827                    + (mediaStatus ? "mounted" : "unmounted"));
18828            if (DEBUG_SD_INSTALL)
18829                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18830                        + ", mMediaMounted=" + mMediaMounted);
18831            if (mediaStatus == mMediaMounted) {
18832                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18833                        : 0, -1);
18834                mHandler.sendMessage(msg);
18835                return;
18836            }
18837            mMediaMounted = mediaStatus;
18838        }
18839        // Queue up an async operation since the package installation may take a
18840        // little while.
18841        mHandler.post(new Runnable() {
18842            public void run() {
18843                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18844            }
18845        });
18846    }
18847
18848    /**
18849     * Called by MountService when the initial ASECs to scan are available.
18850     * Should block until all the ASEC containers are finished being scanned.
18851     */
18852    public void scanAvailableAsecs() {
18853        updateExternalMediaStatusInner(true, false, false);
18854    }
18855
18856    /*
18857     * Collect information of applications on external media, map them against
18858     * existing containers and update information based on current mount status.
18859     * Please note that we always have to report status if reportStatus has been
18860     * set to true especially when unloading packages.
18861     */
18862    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18863            boolean externalStorage) {
18864        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18865        int[] uidArr = EmptyArray.INT;
18866
18867        final String[] list = PackageHelper.getSecureContainerList();
18868        if (ArrayUtils.isEmpty(list)) {
18869            Log.i(TAG, "No secure containers found");
18870        } else {
18871            // Process list of secure containers and categorize them
18872            // as active or stale based on their package internal state.
18873
18874            // reader
18875            synchronized (mPackages) {
18876                for (String cid : list) {
18877                    // Leave stages untouched for now; installer service owns them
18878                    if (PackageInstallerService.isStageName(cid)) continue;
18879
18880                    if (DEBUG_SD_INSTALL)
18881                        Log.i(TAG, "Processing container " + cid);
18882                    String pkgName = getAsecPackageName(cid);
18883                    if (pkgName == null) {
18884                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18885                        continue;
18886                    }
18887                    if (DEBUG_SD_INSTALL)
18888                        Log.i(TAG, "Looking for pkg : " + pkgName);
18889
18890                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18891                    if (ps == null) {
18892                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18893                        continue;
18894                    }
18895
18896                    /*
18897                     * Skip packages that are not external if we're unmounting
18898                     * external storage.
18899                     */
18900                    if (externalStorage && !isMounted && !isExternal(ps)) {
18901                        continue;
18902                    }
18903
18904                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18905                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18906                    // The package status is changed only if the code path
18907                    // matches between settings and the container id.
18908                    if (ps.codePathString != null
18909                            && ps.codePathString.startsWith(args.getCodePath())) {
18910                        if (DEBUG_SD_INSTALL) {
18911                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18912                                    + " at code path: " + ps.codePathString);
18913                        }
18914
18915                        // We do have a valid package installed on sdcard
18916                        processCids.put(args, ps.codePathString);
18917                        final int uid = ps.appId;
18918                        if (uid != -1) {
18919                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18920                        }
18921                    } else {
18922                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18923                                + ps.codePathString);
18924                    }
18925                }
18926            }
18927
18928            Arrays.sort(uidArr);
18929        }
18930
18931        // Process packages with valid entries.
18932        if (isMounted) {
18933            if (DEBUG_SD_INSTALL)
18934                Log.i(TAG, "Loading packages");
18935            loadMediaPackages(processCids, uidArr, externalStorage);
18936            startCleaningPackages();
18937            mInstallerService.onSecureContainersAvailable();
18938        } else {
18939            if (DEBUG_SD_INSTALL)
18940                Log.i(TAG, "Unloading packages");
18941            unloadMediaPackages(processCids, uidArr, reportStatus);
18942        }
18943    }
18944
18945    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18946            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18947        final int size = infos.size();
18948        final String[] packageNames = new String[size];
18949        final int[] packageUids = new int[size];
18950        for (int i = 0; i < size; i++) {
18951            final ApplicationInfo info = infos.get(i);
18952            packageNames[i] = info.packageName;
18953            packageUids[i] = info.uid;
18954        }
18955        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18956                finishedReceiver);
18957    }
18958
18959    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18960            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18961        sendResourcesChangedBroadcast(mediaStatus, replacing,
18962                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18963    }
18964
18965    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18966            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18967        int size = pkgList.length;
18968        if (size > 0) {
18969            // Send broadcasts here
18970            Bundle extras = new Bundle();
18971            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18972            if (uidArr != null) {
18973                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18974            }
18975            if (replacing) {
18976                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18977            }
18978            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18979                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18980            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18981        }
18982    }
18983
18984   /*
18985     * Look at potentially valid container ids from processCids If package
18986     * information doesn't match the one on record or package scanning fails,
18987     * the cid is added to list of removeCids. We currently don't delete stale
18988     * containers.
18989     */
18990    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18991            boolean externalStorage) {
18992        ArrayList<String> pkgList = new ArrayList<String>();
18993        Set<AsecInstallArgs> keys = processCids.keySet();
18994
18995        for (AsecInstallArgs args : keys) {
18996            String codePath = processCids.get(args);
18997            if (DEBUG_SD_INSTALL)
18998                Log.i(TAG, "Loading container : " + args.cid);
18999            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19000            try {
19001                // Make sure there are no container errors first.
19002                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19003                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19004                            + " when installing from sdcard");
19005                    continue;
19006                }
19007                // Check code path here.
19008                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19009                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19010                            + " does not match one in settings " + codePath);
19011                    continue;
19012                }
19013                // Parse package
19014                int parseFlags = mDefParseFlags;
19015                if (args.isExternalAsec()) {
19016                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19017                }
19018                if (args.isFwdLocked()) {
19019                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19020                }
19021
19022                synchronized (mInstallLock) {
19023                    PackageParser.Package pkg = null;
19024                    try {
19025                        // Sadly we don't know the package name yet to freeze it
19026                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19027                                SCAN_IGNORE_FROZEN, 0, null);
19028                    } catch (PackageManagerException e) {
19029                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19030                    }
19031                    // Scan the package
19032                    if (pkg != null) {
19033                        /*
19034                         * TODO why is the lock being held? doPostInstall is
19035                         * called in other places without the lock. This needs
19036                         * to be straightened out.
19037                         */
19038                        // writer
19039                        synchronized (mPackages) {
19040                            retCode = PackageManager.INSTALL_SUCCEEDED;
19041                            pkgList.add(pkg.packageName);
19042                            // Post process args
19043                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19044                                    pkg.applicationInfo.uid);
19045                        }
19046                    } else {
19047                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19048                    }
19049                }
19050
19051            } finally {
19052                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19053                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19054                }
19055            }
19056        }
19057        // writer
19058        synchronized (mPackages) {
19059            // If the platform SDK has changed since the last time we booted,
19060            // we need to re-grant app permission to catch any new ones that
19061            // appear. This is really a hack, and means that apps can in some
19062            // cases get permissions that the user didn't initially explicitly
19063            // allow... it would be nice to have some better way to handle
19064            // this situation.
19065            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19066                    : mSettings.getInternalVersion();
19067            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19068                    : StorageManager.UUID_PRIVATE_INTERNAL;
19069
19070            int updateFlags = UPDATE_PERMISSIONS_ALL;
19071            if (ver.sdkVersion != mSdkVersion) {
19072                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19073                        + mSdkVersion + "; regranting permissions for external");
19074                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19075            }
19076            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19077
19078            // Yay, everything is now upgraded
19079            ver.forceCurrent();
19080
19081            // can downgrade to reader
19082            // Persist settings
19083            mSettings.writeLPr();
19084        }
19085        // Send a broadcast to let everyone know we are done processing
19086        if (pkgList.size() > 0) {
19087            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19088        }
19089    }
19090
19091   /*
19092     * Utility method to unload a list of specified containers
19093     */
19094    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19095        // Just unmount all valid containers.
19096        for (AsecInstallArgs arg : cidArgs) {
19097            synchronized (mInstallLock) {
19098                arg.doPostDeleteLI(false);
19099           }
19100       }
19101   }
19102
19103    /*
19104     * Unload packages mounted on external media. This involves deleting package
19105     * data from internal structures, sending broadcasts about disabled packages,
19106     * gc'ing to free up references, unmounting all secure containers
19107     * corresponding to packages on external media, and posting a
19108     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19109     * that we always have to post this message if status has been requested no
19110     * matter what.
19111     */
19112    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19113            final boolean reportStatus) {
19114        if (DEBUG_SD_INSTALL)
19115            Log.i(TAG, "unloading media packages");
19116        ArrayList<String> pkgList = new ArrayList<String>();
19117        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19118        final Set<AsecInstallArgs> keys = processCids.keySet();
19119        for (AsecInstallArgs args : keys) {
19120            String pkgName = args.getPackageName();
19121            if (DEBUG_SD_INSTALL)
19122                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19123            // Delete package internally
19124            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19125            synchronized (mInstallLock) {
19126                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19127                final boolean res;
19128                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19129                        "unloadMediaPackages")) {
19130                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19131                            null);
19132                }
19133                if (res) {
19134                    pkgList.add(pkgName);
19135                } else {
19136                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19137                    failedList.add(args);
19138                }
19139            }
19140        }
19141
19142        // reader
19143        synchronized (mPackages) {
19144            // We didn't update the settings after removing each package;
19145            // write them now for all packages.
19146            mSettings.writeLPr();
19147        }
19148
19149        // We have to absolutely send UPDATED_MEDIA_STATUS only
19150        // after confirming that all the receivers processed the ordered
19151        // broadcast when packages get disabled, force a gc to clean things up.
19152        // and unload all the containers.
19153        if (pkgList.size() > 0) {
19154            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19155                    new IIntentReceiver.Stub() {
19156                public void performReceive(Intent intent, int resultCode, String data,
19157                        Bundle extras, boolean ordered, boolean sticky,
19158                        int sendingUser) throws RemoteException {
19159                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19160                            reportStatus ? 1 : 0, 1, keys);
19161                    mHandler.sendMessage(msg);
19162                }
19163            });
19164        } else {
19165            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19166                    keys);
19167            mHandler.sendMessage(msg);
19168        }
19169    }
19170
19171    private void loadPrivatePackages(final VolumeInfo vol) {
19172        mHandler.post(new Runnable() {
19173            @Override
19174            public void run() {
19175                loadPrivatePackagesInner(vol);
19176            }
19177        });
19178    }
19179
19180    private void loadPrivatePackagesInner(VolumeInfo vol) {
19181        final String volumeUuid = vol.fsUuid;
19182        if (TextUtils.isEmpty(volumeUuid)) {
19183            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19184            return;
19185        }
19186
19187        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19188        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19189        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19190
19191        final VersionInfo ver;
19192        final List<PackageSetting> packages;
19193        synchronized (mPackages) {
19194            ver = mSettings.findOrCreateVersion(volumeUuid);
19195            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19196        }
19197
19198        for (PackageSetting ps : packages) {
19199            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19200            synchronized (mInstallLock) {
19201                final PackageParser.Package pkg;
19202                try {
19203                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19204                    loaded.add(pkg.applicationInfo);
19205
19206                } catch (PackageManagerException e) {
19207                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19208                }
19209
19210                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19211                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19212                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19213                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19214                }
19215            }
19216        }
19217
19218        // Reconcile app data for all started/unlocked users
19219        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19220        final UserManager um = mContext.getSystemService(UserManager.class);
19221        UserManagerInternal umInternal = getUserManagerInternal();
19222        for (UserInfo user : um.getUsers()) {
19223            final int flags;
19224            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19225                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19226            } else if (umInternal.isUserRunning(user.id)) {
19227                flags = StorageManager.FLAG_STORAGE_DE;
19228            } else {
19229                continue;
19230            }
19231
19232            try {
19233                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19234                synchronized (mInstallLock) {
19235                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
19236                }
19237            } catch (IllegalStateException e) {
19238                // Device was probably ejected, and we'll process that event momentarily
19239                Slog.w(TAG, "Failed to prepare storage: " + e);
19240            }
19241        }
19242
19243        synchronized (mPackages) {
19244            int updateFlags = UPDATE_PERMISSIONS_ALL;
19245            if (ver.sdkVersion != mSdkVersion) {
19246                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19247                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19248                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19249            }
19250            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19251
19252            // Yay, everything is now upgraded
19253            ver.forceCurrent();
19254
19255            mSettings.writeLPr();
19256        }
19257
19258        for (PackageFreezer freezer : freezers) {
19259            freezer.close();
19260        }
19261
19262        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19263        sendResourcesChangedBroadcast(true, false, loaded, null);
19264    }
19265
19266    private void unloadPrivatePackages(final VolumeInfo vol) {
19267        mHandler.post(new Runnable() {
19268            @Override
19269            public void run() {
19270                unloadPrivatePackagesInner(vol);
19271            }
19272        });
19273    }
19274
19275    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19276        final String volumeUuid = vol.fsUuid;
19277        if (TextUtils.isEmpty(volumeUuid)) {
19278            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19279            return;
19280        }
19281
19282        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19283        synchronized (mInstallLock) {
19284        synchronized (mPackages) {
19285            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19286            for (PackageSetting ps : packages) {
19287                if (ps.pkg == null) continue;
19288
19289                final ApplicationInfo info = ps.pkg.applicationInfo;
19290                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19291                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19292
19293                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19294                        "unloadPrivatePackagesInner")) {
19295                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19296                            false, null)) {
19297                        unloaded.add(info);
19298                    } else {
19299                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19300                    }
19301                }
19302
19303                // Try very hard to release any references to this package
19304                // so we don't risk the system server being killed due to
19305                // open FDs
19306                AttributeCache.instance().removePackage(ps.name);
19307            }
19308
19309            mSettings.writeLPr();
19310        }
19311        }
19312
19313        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19314        sendResourcesChangedBroadcast(false, false, unloaded, null);
19315
19316        // Try very hard to release any references to this path so we don't risk
19317        // the system server being killed due to open FDs
19318        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19319
19320        for (int i = 0; i < 3; i++) {
19321            System.gc();
19322            System.runFinalization();
19323        }
19324    }
19325
19326    /**
19327     * Prepare storage areas for given user on all mounted devices.
19328     */
19329    void prepareUserData(int userId, int userSerial, int flags) {
19330        synchronized (mInstallLock) {
19331            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19332            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19333                final String volumeUuid = vol.getFsUuid();
19334                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19335            }
19336        }
19337    }
19338
19339    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19340            boolean allowRecover) {
19341        // Prepare storage and verify that serial numbers are consistent; if
19342        // there's a mismatch we need to destroy to avoid leaking data
19343        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19344        try {
19345            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19346
19347            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19348                UserManagerService.enforceSerialNumber(
19349                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19350                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19351                    UserManagerService.enforceSerialNumber(
19352                            Environment.getDataSystemDeDirectory(userId), userSerial);
19353                }
19354            }
19355            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19356                UserManagerService.enforceSerialNumber(
19357                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19358                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19359                    UserManagerService.enforceSerialNumber(
19360                            Environment.getDataSystemCeDirectory(userId), userSerial);
19361                }
19362            }
19363
19364            synchronized (mInstallLock) {
19365                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19366            }
19367        } catch (Exception e) {
19368            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19369                    + " because we failed to prepare: " + e);
19370            destroyUserDataLI(volumeUuid, userId,
19371                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19372
19373            if (allowRecover) {
19374                // Try one last time; if we fail again we're really in trouble
19375                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19376            }
19377        }
19378    }
19379
19380    /**
19381     * Destroy storage areas for given user on all mounted devices.
19382     */
19383    void destroyUserData(int userId, int flags) {
19384        synchronized (mInstallLock) {
19385            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19386            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19387                final String volumeUuid = vol.getFsUuid();
19388                destroyUserDataLI(volumeUuid, userId, flags);
19389            }
19390        }
19391    }
19392
19393    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19394        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19395        try {
19396            // Clean up app data, profile data, and media data
19397            mInstaller.destroyUserData(volumeUuid, userId, flags);
19398
19399            // Clean up system data
19400            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19401                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19402                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19403                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19404                }
19405                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19406                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19407                }
19408            }
19409
19410            // Data with special labels is now gone, so finish the job
19411            storage.destroyUserStorage(volumeUuid, userId, flags);
19412
19413        } catch (Exception e) {
19414            logCriticalInfo(Log.WARN,
19415                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19416        }
19417    }
19418
19419    /**
19420     * Examine all users present on given mounted volume, and destroy data
19421     * belonging to users that are no longer valid, or whose user ID has been
19422     * recycled.
19423     */
19424    private void reconcileUsers(String volumeUuid) {
19425        final List<File> files = new ArrayList<>();
19426        Collections.addAll(files, FileUtils
19427                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19428        Collections.addAll(files, FileUtils
19429                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19430        Collections.addAll(files, FileUtils
19431                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19432        Collections.addAll(files, FileUtils
19433                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19434        for (File file : files) {
19435            if (!file.isDirectory()) continue;
19436
19437            final int userId;
19438            final UserInfo info;
19439            try {
19440                userId = Integer.parseInt(file.getName());
19441                info = sUserManager.getUserInfo(userId);
19442            } catch (NumberFormatException e) {
19443                Slog.w(TAG, "Invalid user directory " + file);
19444                continue;
19445            }
19446
19447            boolean destroyUser = false;
19448            if (info == null) {
19449                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19450                        + " because no matching user was found");
19451                destroyUser = true;
19452            } else if (!mOnlyCore) {
19453                try {
19454                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19455                } catch (IOException e) {
19456                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19457                            + " because we failed to enforce serial number: " + e);
19458                    destroyUser = true;
19459                }
19460            }
19461
19462            if (destroyUser) {
19463                synchronized (mInstallLock) {
19464                    destroyUserDataLI(volumeUuid, userId,
19465                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19466                }
19467            }
19468        }
19469    }
19470
19471    private void assertPackageKnown(String volumeUuid, String packageName)
19472            throws PackageManagerException {
19473        synchronized (mPackages) {
19474            final PackageSetting ps = mSettings.mPackages.get(packageName);
19475            if (ps == null) {
19476                throw new PackageManagerException("Package " + packageName + " is unknown");
19477            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19478                throw new PackageManagerException(
19479                        "Package " + packageName + " found on unknown volume " + volumeUuid
19480                                + "; expected volume " + ps.volumeUuid);
19481            }
19482        }
19483    }
19484
19485    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19486            throws PackageManagerException {
19487        synchronized (mPackages) {
19488            final PackageSetting ps = mSettings.mPackages.get(packageName);
19489            if (ps == null) {
19490                throw new PackageManagerException("Package " + packageName + " is unknown");
19491            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19492                throw new PackageManagerException(
19493                        "Package " + packageName + " found on unknown volume " + volumeUuid
19494                                + "; expected volume " + ps.volumeUuid);
19495            } else if (!ps.getInstalled(userId)) {
19496                throw new PackageManagerException(
19497                        "Package " + packageName + " not installed for user " + userId);
19498            }
19499        }
19500    }
19501
19502    /**
19503     * Examine all apps present on given mounted volume, and destroy apps that
19504     * aren't expected, either due to uninstallation or reinstallation on
19505     * another volume.
19506     */
19507    private void reconcileApps(String volumeUuid) {
19508        final File[] files = FileUtils
19509                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19510        for (File file : files) {
19511            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19512                    && !PackageInstallerService.isStageName(file.getName());
19513            if (!isPackage) {
19514                // Ignore entries which are not packages
19515                continue;
19516            }
19517
19518            try {
19519                final PackageLite pkg = PackageParser.parsePackageLite(file,
19520                        PackageParser.PARSE_MUST_BE_APK);
19521                assertPackageKnown(volumeUuid, pkg.packageName);
19522
19523            } catch (PackageParserException | PackageManagerException e) {
19524                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19525                synchronized (mInstallLock) {
19526                    removeCodePathLI(file);
19527                }
19528            }
19529        }
19530    }
19531
19532    /**
19533     * Reconcile all app data for the given user.
19534     * <p>
19535     * Verifies that directories exist and that ownership and labeling is
19536     * correct for all installed apps on all mounted volumes.
19537     */
19538    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
19539        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19540        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19541            final String volumeUuid = vol.getFsUuid();
19542            synchronized (mInstallLock) {
19543                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
19544            }
19545        }
19546    }
19547
19548    /**
19549     * Reconcile all app data on given mounted volume.
19550     * <p>
19551     * Destroys app data that isn't expected, either due to uninstallation or
19552     * reinstallation on another volume.
19553     * <p>
19554     * Verifies that directories exist and that ownership and labeling is
19555     * correct for all installed apps.
19556     */
19557    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
19558            boolean migrateAppData) {
19559        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19560                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
19561
19562        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19563        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19564
19565        boolean restoreconNeeded = false;
19566
19567        // First look for stale data that doesn't belong, and check if things
19568        // have changed since we did our last restorecon
19569        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19570            if (StorageManager.isFileEncryptedNativeOrEmulated()
19571                    && !StorageManager.isUserKeyUnlocked(userId)) {
19572                throw new RuntimeException(
19573                        "Yikes, someone asked us to reconcile CE storage while " + userId
19574                                + " was still locked; this would have caused massive data loss!");
19575            }
19576
19577            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19578
19579            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19580            for (File file : files) {
19581                final String packageName = file.getName();
19582                try {
19583                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19584                } catch (PackageManagerException e) {
19585                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19586                    try {
19587                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19588                                StorageManager.FLAG_STORAGE_CE, 0);
19589                    } catch (InstallerException e2) {
19590                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19591                    }
19592                }
19593            }
19594        }
19595        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19596            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19597
19598            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19599            for (File file : files) {
19600                final String packageName = file.getName();
19601                try {
19602                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19603                } catch (PackageManagerException e) {
19604                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19605                    try {
19606                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19607                                StorageManager.FLAG_STORAGE_DE, 0);
19608                    } catch (InstallerException e2) {
19609                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19610                    }
19611                }
19612            }
19613        }
19614
19615        // Ensure that data directories are ready to roll for all packages
19616        // installed for this volume and user
19617        final List<PackageSetting> packages;
19618        synchronized (mPackages) {
19619            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19620        }
19621        int preparedCount = 0;
19622        for (PackageSetting ps : packages) {
19623            final String packageName = ps.name;
19624            if (ps.pkg == null) {
19625                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19626                // TODO: might be due to legacy ASEC apps; we should circle back
19627                // and reconcile again once they're scanned
19628                continue;
19629            }
19630
19631            if (ps.getInstalled(userId)) {
19632                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19633
19634                if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) {
19635                    // We may have just shuffled around app data directories, so
19636                    // prepare them one more time
19637                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19638                }
19639
19640                preparedCount++;
19641            }
19642        }
19643
19644        if (restoreconNeeded) {
19645            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19646                SELinuxMMAC.setRestoreconDone(ceDir);
19647            }
19648            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19649                SELinuxMMAC.setRestoreconDone(deDir);
19650            }
19651        }
19652
19653        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19654                + " packages; restoreconNeeded was " + restoreconNeeded);
19655    }
19656
19657    /**
19658     * Prepare app data for the given app just after it was installed or
19659     * upgraded. This method carefully only touches users that it's installed
19660     * for, and it forces a restorecon to handle any seinfo changes.
19661     * <p>
19662     * Verifies that directories exist and that ownership and labeling is
19663     * correct for all installed apps. If there is an ownership mismatch, it
19664     * will try recovering system apps by wiping data; third-party app data is
19665     * left intact.
19666     * <p>
19667     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19668     */
19669    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19670        final PackageSetting ps;
19671        synchronized (mPackages) {
19672            ps = mSettings.mPackages.get(pkg.packageName);
19673            mSettings.writeKernelMappingLPr(ps);
19674        }
19675
19676        final UserManager um = mContext.getSystemService(UserManager.class);
19677        UserManagerInternal umInternal = getUserManagerInternal();
19678        for (UserInfo user : um.getUsers()) {
19679            final int flags;
19680            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19681                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19682            } else if (umInternal.isUserRunning(user.id)) {
19683                flags = StorageManager.FLAG_STORAGE_DE;
19684            } else {
19685                continue;
19686            }
19687
19688            if (ps.getInstalled(user.id)) {
19689                // Whenever an app changes, force a restorecon of its data
19690                // TODO: when user data is locked, mark that we're still dirty
19691                prepareAppDataLIF(pkg, user.id, flags, true);
19692            }
19693        }
19694    }
19695
19696    /**
19697     * Prepare app data for the given app.
19698     * <p>
19699     * Verifies that directories exist and that ownership and labeling is
19700     * correct for all installed apps. If there is an ownership mismatch, this
19701     * will try recovering system apps by wiping data; third-party app data is
19702     * left intact.
19703     */
19704    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19705            boolean restoreconNeeded) {
19706        if (pkg == null) {
19707            Slog.wtf(TAG, "Package was null!", new Throwable());
19708            return;
19709        }
19710        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19711        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19712        for (int i = 0; i < childCount; i++) {
19713            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19714        }
19715    }
19716
19717    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19718            boolean restoreconNeeded) {
19719        if (DEBUG_APP_DATA) {
19720            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19721                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19722        }
19723
19724        final String volumeUuid = pkg.volumeUuid;
19725        final String packageName = pkg.packageName;
19726        final ApplicationInfo app = pkg.applicationInfo;
19727        final int appId = UserHandle.getAppId(app.uid);
19728
19729        Preconditions.checkNotNull(app.seinfo);
19730
19731        try {
19732            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19733                    appId, app.seinfo, app.targetSdkVersion);
19734        } catch (InstallerException e) {
19735            if (app.isSystemApp()) {
19736                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19737                        + ", but trying to recover: " + e);
19738                destroyAppDataLeafLIF(pkg, userId, flags);
19739                try {
19740                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19741                            appId, app.seinfo, app.targetSdkVersion);
19742                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19743                } catch (InstallerException e2) {
19744                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19745                }
19746            } else {
19747                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19748            }
19749        }
19750
19751        if (restoreconNeeded) {
19752            try {
19753                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19754                        app.seinfo);
19755            } catch (InstallerException e) {
19756                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19757            }
19758        }
19759
19760        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19761            try {
19762                // CE storage is unlocked right now, so read out the inode and
19763                // remember for use later when it's locked
19764                // TODO: mark this structure as dirty so we persist it!
19765                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19766                        StorageManager.FLAG_STORAGE_CE);
19767                synchronized (mPackages) {
19768                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19769                    if (ps != null) {
19770                        ps.setCeDataInode(ceDataInode, userId);
19771                    }
19772                }
19773            } catch (InstallerException e) {
19774                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19775            }
19776        }
19777
19778        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19779    }
19780
19781    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19782        if (pkg == null) {
19783            Slog.wtf(TAG, "Package was null!", new Throwable());
19784            return;
19785        }
19786        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19787        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19788        for (int i = 0; i < childCount; i++) {
19789            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19790        }
19791    }
19792
19793    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19794        final String volumeUuid = pkg.volumeUuid;
19795        final String packageName = pkg.packageName;
19796        final ApplicationInfo app = pkg.applicationInfo;
19797
19798        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19799            // Create a native library symlink only if we have native libraries
19800            // and if the native libraries are 32 bit libraries. We do not provide
19801            // this symlink for 64 bit libraries.
19802            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19803                final String nativeLibPath = app.nativeLibraryDir;
19804                try {
19805                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19806                            nativeLibPath, userId);
19807                } catch (InstallerException e) {
19808                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19809                }
19810            }
19811        }
19812    }
19813
19814    /**
19815     * For system apps on non-FBE devices, this method migrates any existing
19816     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19817     * requested by the app.
19818     */
19819    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19820        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19821                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19822            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19823                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19824            try {
19825                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19826                        storageTarget);
19827            } catch (InstallerException e) {
19828                logCriticalInfo(Log.WARN,
19829                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19830            }
19831            return true;
19832        } else {
19833            return false;
19834        }
19835    }
19836
19837    public PackageFreezer freezePackage(String packageName, String killReason) {
19838        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
19839    }
19840
19841    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
19842        return new PackageFreezer(packageName, userId, killReason);
19843    }
19844
19845    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19846            String killReason) {
19847        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
19848    }
19849
19850    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
19851            String killReason) {
19852        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19853            return new PackageFreezer();
19854        } else {
19855            return freezePackage(packageName, userId, killReason);
19856        }
19857    }
19858
19859    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19860            String killReason) {
19861        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
19862    }
19863
19864    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
19865            String killReason) {
19866        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19867            return new PackageFreezer();
19868        } else {
19869            return freezePackage(packageName, userId, killReason);
19870        }
19871    }
19872
19873    /**
19874     * Class that freezes and kills the given package upon creation, and
19875     * unfreezes it upon closing. This is typically used when doing surgery on
19876     * app code/data to prevent the app from running while you're working.
19877     */
19878    private class PackageFreezer implements AutoCloseable {
19879        private final String mPackageName;
19880        private final PackageFreezer[] mChildren;
19881
19882        private final boolean mWeFroze;
19883
19884        private final AtomicBoolean mClosed = new AtomicBoolean();
19885        private final CloseGuard mCloseGuard = CloseGuard.get();
19886
19887        /**
19888         * Create and return a stub freezer that doesn't actually do anything,
19889         * typically used when someone requested
19890         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19891         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19892         */
19893        public PackageFreezer() {
19894            mPackageName = null;
19895            mChildren = null;
19896            mWeFroze = false;
19897            mCloseGuard.open("close");
19898        }
19899
19900        public PackageFreezer(String packageName, int userId, String killReason) {
19901            synchronized (mPackages) {
19902                mPackageName = packageName;
19903                mWeFroze = mFrozenPackages.add(mPackageName);
19904
19905                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19906                if (ps != null) {
19907                    killApplication(ps.name, ps.appId, userId, killReason);
19908                }
19909
19910                final PackageParser.Package p = mPackages.get(packageName);
19911                if (p != null && p.childPackages != null) {
19912                    final int N = p.childPackages.size();
19913                    mChildren = new PackageFreezer[N];
19914                    for (int i = 0; i < N; i++) {
19915                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19916                                userId, killReason);
19917                    }
19918                } else {
19919                    mChildren = null;
19920                }
19921            }
19922            mCloseGuard.open("close");
19923        }
19924
19925        @Override
19926        protected void finalize() throws Throwable {
19927            try {
19928                mCloseGuard.warnIfOpen();
19929                close();
19930            } finally {
19931                super.finalize();
19932            }
19933        }
19934
19935        @Override
19936        public void close() {
19937            mCloseGuard.close();
19938            if (mClosed.compareAndSet(false, true)) {
19939                synchronized (mPackages) {
19940                    if (mWeFroze) {
19941                        mFrozenPackages.remove(mPackageName);
19942                    }
19943
19944                    if (mChildren != null) {
19945                        for (PackageFreezer freezer : mChildren) {
19946                            freezer.close();
19947                        }
19948                    }
19949                }
19950            }
19951        }
19952    }
19953
19954    /**
19955     * Verify that given package is currently frozen.
19956     */
19957    private void checkPackageFrozen(String packageName) {
19958        synchronized (mPackages) {
19959            if (!mFrozenPackages.contains(packageName)) {
19960                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19961            }
19962        }
19963    }
19964
19965    @Override
19966    public int movePackage(final String packageName, final String volumeUuid) {
19967        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19968
19969        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19970        final int moveId = mNextMoveId.getAndIncrement();
19971        mHandler.post(new Runnable() {
19972            @Override
19973            public void run() {
19974                try {
19975                    movePackageInternal(packageName, volumeUuid, moveId, user);
19976                } catch (PackageManagerException e) {
19977                    Slog.w(TAG, "Failed to move " + packageName, e);
19978                    mMoveCallbacks.notifyStatusChanged(moveId,
19979                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19980                }
19981            }
19982        });
19983        return moveId;
19984    }
19985
19986    private void movePackageInternal(final String packageName, final String volumeUuid,
19987            final int moveId, UserHandle user) throws PackageManagerException {
19988        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19989        final PackageManager pm = mContext.getPackageManager();
19990
19991        final boolean currentAsec;
19992        final String currentVolumeUuid;
19993        final File codeFile;
19994        final String installerPackageName;
19995        final String packageAbiOverride;
19996        final int appId;
19997        final String seinfo;
19998        final String label;
19999        final int targetSdkVersion;
20000        final PackageFreezer freezer;
20001        final int[] installedUserIds;
20002
20003        // reader
20004        synchronized (mPackages) {
20005            final PackageParser.Package pkg = mPackages.get(packageName);
20006            final PackageSetting ps = mSettings.mPackages.get(packageName);
20007            if (pkg == null || ps == null) {
20008                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20009            }
20010
20011            if (pkg.applicationInfo.isSystemApp()) {
20012                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20013                        "Cannot move system application");
20014            }
20015
20016            if (pkg.applicationInfo.isExternalAsec()) {
20017                currentAsec = true;
20018                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20019            } else if (pkg.applicationInfo.isForwardLocked()) {
20020                currentAsec = true;
20021                currentVolumeUuid = "forward_locked";
20022            } else {
20023                currentAsec = false;
20024                currentVolumeUuid = ps.volumeUuid;
20025
20026                final File probe = new File(pkg.codePath);
20027                final File probeOat = new File(probe, "oat");
20028                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20029                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20030                            "Move only supported for modern cluster style installs");
20031                }
20032            }
20033
20034            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20035                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20036                        "Package already moved to " + volumeUuid);
20037            }
20038            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20039                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20040                        "Device admin cannot be moved");
20041            }
20042
20043            if (mFrozenPackages.contains(packageName)) {
20044                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20045                        "Failed to move already frozen package");
20046            }
20047
20048            codeFile = new File(pkg.codePath);
20049            installerPackageName = ps.installerPackageName;
20050            packageAbiOverride = ps.cpuAbiOverrideString;
20051            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20052            seinfo = pkg.applicationInfo.seinfo;
20053            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20054            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20055            freezer = freezePackage(packageName, "movePackageInternal");
20056            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20057        }
20058
20059        final Bundle extras = new Bundle();
20060        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20061        extras.putString(Intent.EXTRA_TITLE, label);
20062        mMoveCallbacks.notifyCreated(moveId, extras);
20063
20064        int installFlags;
20065        final boolean moveCompleteApp;
20066        final File measurePath;
20067
20068        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20069            installFlags = INSTALL_INTERNAL;
20070            moveCompleteApp = !currentAsec;
20071            measurePath = Environment.getDataAppDirectory(volumeUuid);
20072        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20073            installFlags = INSTALL_EXTERNAL;
20074            moveCompleteApp = false;
20075            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20076        } else {
20077            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20078            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20079                    || !volume.isMountedWritable()) {
20080                freezer.close();
20081                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20082                        "Move location not mounted private volume");
20083            }
20084
20085            Preconditions.checkState(!currentAsec);
20086
20087            installFlags = INSTALL_INTERNAL;
20088            moveCompleteApp = true;
20089            measurePath = Environment.getDataAppDirectory(volumeUuid);
20090        }
20091
20092        final PackageStats stats = new PackageStats(null, -1);
20093        synchronized (mInstaller) {
20094            for (int userId : installedUserIds) {
20095                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20096                    freezer.close();
20097                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20098                            "Failed to measure package size");
20099                }
20100            }
20101        }
20102
20103        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20104                + stats.dataSize);
20105
20106        final long startFreeBytes = measurePath.getFreeSpace();
20107        final long sizeBytes;
20108        if (moveCompleteApp) {
20109            sizeBytes = stats.codeSize + stats.dataSize;
20110        } else {
20111            sizeBytes = stats.codeSize;
20112        }
20113
20114        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20115            freezer.close();
20116            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20117                    "Not enough free space to move");
20118        }
20119
20120        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20121
20122        final CountDownLatch installedLatch = new CountDownLatch(1);
20123        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20124            @Override
20125            public void onUserActionRequired(Intent intent) throws RemoteException {
20126                throw new IllegalStateException();
20127            }
20128
20129            @Override
20130            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20131                    Bundle extras) throws RemoteException {
20132                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20133                        + PackageManager.installStatusToString(returnCode, msg));
20134
20135                installedLatch.countDown();
20136                freezer.close();
20137
20138                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20139                switch (status) {
20140                    case PackageInstaller.STATUS_SUCCESS:
20141                        mMoveCallbacks.notifyStatusChanged(moveId,
20142                                PackageManager.MOVE_SUCCEEDED);
20143                        break;
20144                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20145                        mMoveCallbacks.notifyStatusChanged(moveId,
20146                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20147                        break;
20148                    default:
20149                        mMoveCallbacks.notifyStatusChanged(moveId,
20150                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20151                        break;
20152                }
20153            }
20154        };
20155
20156        final MoveInfo move;
20157        if (moveCompleteApp) {
20158            // Kick off a thread to report progress estimates
20159            new Thread() {
20160                @Override
20161                public void run() {
20162                    while (true) {
20163                        try {
20164                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20165                                break;
20166                            }
20167                        } catch (InterruptedException ignored) {
20168                        }
20169
20170                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20171                        final int progress = 10 + (int) MathUtils.constrain(
20172                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20173                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20174                    }
20175                }
20176            }.start();
20177
20178            final String dataAppName = codeFile.getName();
20179            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20180                    dataAppName, appId, seinfo, targetSdkVersion);
20181        } else {
20182            move = null;
20183        }
20184
20185        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20186
20187        final Message msg = mHandler.obtainMessage(INIT_COPY);
20188        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20189        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20190                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20191                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20192        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20193        msg.obj = params;
20194
20195        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20196                System.identityHashCode(msg.obj));
20197        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20198                System.identityHashCode(msg.obj));
20199
20200        mHandler.sendMessage(msg);
20201    }
20202
20203    @Override
20204    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20205        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20206
20207        final int realMoveId = mNextMoveId.getAndIncrement();
20208        final Bundle extras = new Bundle();
20209        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20210        mMoveCallbacks.notifyCreated(realMoveId, extras);
20211
20212        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20213            @Override
20214            public void onCreated(int moveId, Bundle extras) {
20215                // Ignored
20216            }
20217
20218            @Override
20219            public void onStatusChanged(int moveId, int status, long estMillis) {
20220                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20221            }
20222        };
20223
20224        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20225        storage.setPrimaryStorageUuid(volumeUuid, callback);
20226        return realMoveId;
20227    }
20228
20229    @Override
20230    public int getMoveStatus(int moveId) {
20231        mContext.enforceCallingOrSelfPermission(
20232                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20233        return mMoveCallbacks.mLastStatus.get(moveId);
20234    }
20235
20236    @Override
20237    public void registerMoveCallback(IPackageMoveObserver callback) {
20238        mContext.enforceCallingOrSelfPermission(
20239                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20240        mMoveCallbacks.register(callback);
20241    }
20242
20243    @Override
20244    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20245        mContext.enforceCallingOrSelfPermission(
20246                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20247        mMoveCallbacks.unregister(callback);
20248    }
20249
20250    @Override
20251    public boolean setInstallLocation(int loc) {
20252        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20253                null);
20254        if (getInstallLocation() == loc) {
20255            return true;
20256        }
20257        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20258                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20259            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20260                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20261            return true;
20262        }
20263        return false;
20264   }
20265
20266    @Override
20267    public int getInstallLocation() {
20268        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20269                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20270                PackageHelper.APP_INSTALL_AUTO);
20271    }
20272
20273    /** Called by UserManagerService */
20274    void cleanUpUser(UserManagerService userManager, int userHandle) {
20275        synchronized (mPackages) {
20276            mDirtyUsers.remove(userHandle);
20277            mUserNeedsBadging.delete(userHandle);
20278            mSettings.removeUserLPw(userHandle);
20279            mPendingBroadcasts.remove(userHandle);
20280            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20281            removeUnusedPackagesLPw(userManager, userHandle);
20282        }
20283    }
20284
20285    /**
20286     * We're removing userHandle and would like to remove any downloaded packages
20287     * that are no longer in use by any other user.
20288     * @param userHandle the user being removed
20289     */
20290    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20291        final boolean DEBUG_CLEAN_APKS = false;
20292        int [] users = userManager.getUserIds();
20293        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20294        while (psit.hasNext()) {
20295            PackageSetting ps = psit.next();
20296            if (ps.pkg == null) {
20297                continue;
20298            }
20299            final String packageName = ps.pkg.packageName;
20300            // Skip over if system app
20301            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20302                continue;
20303            }
20304            if (DEBUG_CLEAN_APKS) {
20305                Slog.i(TAG, "Checking package " + packageName);
20306            }
20307            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20308            if (keep) {
20309                if (DEBUG_CLEAN_APKS) {
20310                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20311                }
20312            } else {
20313                for (int i = 0; i < users.length; i++) {
20314                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20315                        keep = true;
20316                        if (DEBUG_CLEAN_APKS) {
20317                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20318                                    + users[i]);
20319                        }
20320                        break;
20321                    }
20322                }
20323            }
20324            if (!keep) {
20325                if (DEBUG_CLEAN_APKS) {
20326                    Slog.i(TAG, "  Removing package " + packageName);
20327                }
20328                mHandler.post(new Runnable() {
20329                    public void run() {
20330                        deletePackageX(packageName, userHandle, 0);
20331                    } //end run
20332                });
20333            }
20334        }
20335    }
20336
20337    /** Called by UserManagerService */
20338    void createNewUser(int userId) {
20339        synchronized (mInstallLock) {
20340            mSettings.createNewUserLI(this, mInstaller, userId);
20341        }
20342        synchronized (mPackages) {
20343            scheduleWritePackageRestrictionsLocked(userId);
20344            scheduleWritePackageListLocked(userId);
20345            applyFactoryDefaultBrowserLPw(userId);
20346            primeDomainVerificationsLPw(userId);
20347        }
20348    }
20349
20350    void onNewUserCreated(final int userId) {
20351        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20352        // If permission review for legacy apps is required, we represent
20353        // dagerous permissions for such apps as always granted runtime
20354        // permissions to keep per user flag state whether review is needed.
20355        // Hence, if a new user is added we have to propagate dangerous
20356        // permission grants for these legacy apps.
20357        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20358            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20359                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20360        }
20361    }
20362
20363    @Override
20364    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20365        mContext.enforceCallingOrSelfPermission(
20366                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20367                "Only package verification agents can read the verifier device identity");
20368
20369        synchronized (mPackages) {
20370            return mSettings.getVerifierDeviceIdentityLPw();
20371        }
20372    }
20373
20374    @Override
20375    public void setPermissionEnforced(String permission, boolean enforced) {
20376        // TODO: Now that we no longer change GID for storage, this should to away.
20377        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20378                "setPermissionEnforced");
20379        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20380            synchronized (mPackages) {
20381                if (mSettings.mReadExternalStorageEnforced == null
20382                        || mSettings.mReadExternalStorageEnforced != enforced) {
20383                    mSettings.mReadExternalStorageEnforced = enforced;
20384                    mSettings.writeLPr();
20385                }
20386            }
20387            // kill any non-foreground processes so we restart them and
20388            // grant/revoke the GID.
20389            final IActivityManager am = ActivityManagerNative.getDefault();
20390            if (am != null) {
20391                final long token = Binder.clearCallingIdentity();
20392                try {
20393                    am.killProcessesBelowForeground("setPermissionEnforcement");
20394                } catch (RemoteException e) {
20395                } finally {
20396                    Binder.restoreCallingIdentity(token);
20397                }
20398            }
20399        } else {
20400            throw new IllegalArgumentException("No selective enforcement for " + permission);
20401        }
20402    }
20403
20404    @Override
20405    @Deprecated
20406    public boolean isPermissionEnforced(String permission) {
20407        return true;
20408    }
20409
20410    @Override
20411    public boolean isStorageLow() {
20412        final long token = Binder.clearCallingIdentity();
20413        try {
20414            final DeviceStorageMonitorInternal
20415                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20416            if (dsm != null) {
20417                return dsm.isMemoryLow();
20418            } else {
20419                return false;
20420            }
20421        } finally {
20422            Binder.restoreCallingIdentity(token);
20423        }
20424    }
20425
20426    @Override
20427    public IPackageInstaller getPackageInstaller() {
20428        return mInstallerService;
20429    }
20430
20431    private boolean userNeedsBadging(int userId) {
20432        int index = mUserNeedsBadging.indexOfKey(userId);
20433        if (index < 0) {
20434            final UserInfo userInfo;
20435            final long token = Binder.clearCallingIdentity();
20436            try {
20437                userInfo = sUserManager.getUserInfo(userId);
20438            } finally {
20439                Binder.restoreCallingIdentity(token);
20440            }
20441            final boolean b;
20442            if (userInfo != null && userInfo.isManagedProfile()) {
20443                b = true;
20444            } else {
20445                b = false;
20446            }
20447            mUserNeedsBadging.put(userId, b);
20448            return b;
20449        }
20450        return mUserNeedsBadging.valueAt(index);
20451    }
20452
20453    @Override
20454    public KeySet getKeySetByAlias(String packageName, String alias) {
20455        if (packageName == null || alias == null) {
20456            return null;
20457        }
20458        synchronized(mPackages) {
20459            final PackageParser.Package pkg = mPackages.get(packageName);
20460            if (pkg == null) {
20461                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20462                throw new IllegalArgumentException("Unknown package: " + packageName);
20463            }
20464            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20465            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20466        }
20467    }
20468
20469    @Override
20470    public KeySet getSigningKeySet(String packageName) {
20471        if (packageName == null) {
20472            return null;
20473        }
20474        synchronized(mPackages) {
20475            final PackageParser.Package pkg = mPackages.get(packageName);
20476            if (pkg == null) {
20477                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20478                throw new IllegalArgumentException("Unknown package: " + packageName);
20479            }
20480            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20481                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20482                throw new SecurityException("May not access signing KeySet of other apps.");
20483            }
20484            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20485            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20486        }
20487    }
20488
20489    @Override
20490    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20491        if (packageName == null || ks == null) {
20492            return false;
20493        }
20494        synchronized(mPackages) {
20495            final PackageParser.Package pkg = mPackages.get(packageName);
20496            if (pkg == null) {
20497                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20498                throw new IllegalArgumentException("Unknown package: " + packageName);
20499            }
20500            IBinder ksh = ks.getToken();
20501            if (ksh instanceof KeySetHandle) {
20502                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20503                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20504            }
20505            return false;
20506        }
20507    }
20508
20509    @Override
20510    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20511        if (packageName == null || ks == null) {
20512            return false;
20513        }
20514        synchronized(mPackages) {
20515            final PackageParser.Package pkg = mPackages.get(packageName);
20516            if (pkg == null) {
20517                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20518                throw new IllegalArgumentException("Unknown package: " + packageName);
20519            }
20520            IBinder ksh = ks.getToken();
20521            if (ksh instanceof KeySetHandle) {
20522                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20523                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20524            }
20525            return false;
20526        }
20527    }
20528
20529    private void deletePackageIfUnusedLPr(final String packageName) {
20530        PackageSetting ps = mSettings.mPackages.get(packageName);
20531        if (ps == null) {
20532            return;
20533        }
20534        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20535            // TODO Implement atomic delete if package is unused
20536            // It is currently possible that the package will be deleted even if it is installed
20537            // after this method returns.
20538            mHandler.post(new Runnable() {
20539                public void run() {
20540                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20541                }
20542            });
20543        }
20544    }
20545
20546    /**
20547     * Check and throw if the given before/after packages would be considered a
20548     * downgrade.
20549     */
20550    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20551            throws PackageManagerException {
20552        if (after.versionCode < before.mVersionCode) {
20553            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20554                    "Update version code " + after.versionCode + " is older than current "
20555                    + before.mVersionCode);
20556        } else if (after.versionCode == before.mVersionCode) {
20557            if (after.baseRevisionCode < before.baseRevisionCode) {
20558                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20559                        "Update base revision code " + after.baseRevisionCode
20560                        + " is older than current " + before.baseRevisionCode);
20561            }
20562
20563            if (!ArrayUtils.isEmpty(after.splitNames)) {
20564                for (int i = 0; i < after.splitNames.length; i++) {
20565                    final String splitName = after.splitNames[i];
20566                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20567                    if (j != -1) {
20568                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20569                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20570                                    "Update split " + splitName + " revision code "
20571                                    + after.splitRevisionCodes[i] + " is older than current "
20572                                    + before.splitRevisionCodes[j]);
20573                        }
20574                    }
20575                }
20576            }
20577        }
20578    }
20579
20580    private static class MoveCallbacks extends Handler {
20581        private static final int MSG_CREATED = 1;
20582        private static final int MSG_STATUS_CHANGED = 2;
20583
20584        private final RemoteCallbackList<IPackageMoveObserver>
20585                mCallbacks = new RemoteCallbackList<>();
20586
20587        private final SparseIntArray mLastStatus = new SparseIntArray();
20588
20589        public MoveCallbacks(Looper looper) {
20590            super(looper);
20591        }
20592
20593        public void register(IPackageMoveObserver callback) {
20594            mCallbacks.register(callback);
20595        }
20596
20597        public void unregister(IPackageMoveObserver callback) {
20598            mCallbacks.unregister(callback);
20599        }
20600
20601        @Override
20602        public void handleMessage(Message msg) {
20603            final SomeArgs args = (SomeArgs) msg.obj;
20604            final int n = mCallbacks.beginBroadcast();
20605            for (int i = 0; i < n; i++) {
20606                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20607                try {
20608                    invokeCallback(callback, msg.what, args);
20609                } catch (RemoteException ignored) {
20610                }
20611            }
20612            mCallbacks.finishBroadcast();
20613            args.recycle();
20614        }
20615
20616        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20617                throws RemoteException {
20618            switch (what) {
20619                case MSG_CREATED: {
20620                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20621                    break;
20622                }
20623                case MSG_STATUS_CHANGED: {
20624                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20625                    break;
20626                }
20627            }
20628        }
20629
20630        private void notifyCreated(int moveId, Bundle extras) {
20631            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20632
20633            final SomeArgs args = SomeArgs.obtain();
20634            args.argi1 = moveId;
20635            args.arg2 = extras;
20636            obtainMessage(MSG_CREATED, args).sendToTarget();
20637        }
20638
20639        private void notifyStatusChanged(int moveId, int status) {
20640            notifyStatusChanged(moveId, status, -1);
20641        }
20642
20643        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20644            Slog.v(TAG, "Move " + moveId + " status " + status);
20645
20646            final SomeArgs args = SomeArgs.obtain();
20647            args.argi1 = moveId;
20648            args.argi2 = status;
20649            args.arg3 = estMillis;
20650            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20651
20652            synchronized (mLastStatus) {
20653                mLastStatus.put(moveId, status);
20654            }
20655        }
20656    }
20657
20658    private final static class OnPermissionChangeListeners extends Handler {
20659        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20660
20661        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20662                new RemoteCallbackList<>();
20663
20664        public OnPermissionChangeListeners(Looper looper) {
20665            super(looper);
20666        }
20667
20668        @Override
20669        public void handleMessage(Message msg) {
20670            switch (msg.what) {
20671                case MSG_ON_PERMISSIONS_CHANGED: {
20672                    final int uid = msg.arg1;
20673                    handleOnPermissionsChanged(uid);
20674                } break;
20675            }
20676        }
20677
20678        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20679            mPermissionListeners.register(listener);
20680
20681        }
20682
20683        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20684            mPermissionListeners.unregister(listener);
20685        }
20686
20687        public void onPermissionsChanged(int uid) {
20688            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20689                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20690            }
20691        }
20692
20693        private void handleOnPermissionsChanged(int uid) {
20694            final int count = mPermissionListeners.beginBroadcast();
20695            try {
20696                for (int i = 0; i < count; i++) {
20697                    IOnPermissionsChangeListener callback = mPermissionListeners
20698                            .getBroadcastItem(i);
20699                    try {
20700                        callback.onPermissionsChanged(uid);
20701                    } catch (RemoteException e) {
20702                        Log.e(TAG, "Permission listener is dead", e);
20703                    }
20704                }
20705            } finally {
20706                mPermissionListeners.finishBroadcast();
20707            }
20708        }
20709    }
20710
20711    private class PackageManagerInternalImpl extends PackageManagerInternal {
20712        @Override
20713        public void setLocationPackagesProvider(PackagesProvider provider) {
20714            synchronized (mPackages) {
20715                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20716            }
20717        }
20718
20719        @Override
20720        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20721            synchronized (mPackages) {
20722                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20723            }
20724        }
20725
20726        @Override
20727        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20728            synchronized (mPackages) {
20729                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20730            }
20731        }
20732
20733        @Override
20734        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20735            synchronized (mPackages) {
20736                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20737            }
20738        }
20739
20740        @Override
20741        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20742            synchronized (mPackages) {
20743                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20744            }
20745        }
20746
20747        @Override
20748        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20749            synchronized (mPackages) {
20750                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20751            }
20752        }
20753
20754        @Override
20755        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20756            synchronized (mPackages) {
20757                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20758                        packageName, userId);
20759            }
20760        }
20761
20762        @Override
20763        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20764            synchronized (mPackages) {
20765                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20766                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20767                        packageName, userId);
20768            }
20769        }
20770
20771        @Override
20772        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20773            synchronized (mPackages) {
20774                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20775                        packageName, userId);
20776            }
20777        }
20778
20779        @Override
20780        public void setKeepUninstalledPackages(final List<String> packageList) {
20781            Preconditions.checkNotNull(packageList);
20782            List<String> removedFromList = null;
20783            synchronized (mPackages) {
20784                if (mKeepUninstalledPackages != null) {
20785                    final int packagesCount = mKeepUninstalledPackages.size();
20786                    for (int i = 0; i < packagesCount; i++) {
20787                        String oldPackage = mKeepUninstalledPackages.get(i);
20788                        if (packageList != null && packageList.contains(oldPackage)) {
20789                            continue;
20790                        }
20791                        if (removedFromList == null) {
20792                            removedFromList = new ArrayList<>();
20793                        }
20794                        removedFromList.add(oldPackage);
20795                    }
20796                }
20797                mKeepUninstalledPackages = new ArrayList<>(packageList);
20798                if (removedFromList != null) {
20799                    final int removedCount = removedFromList.size();
20800                    for (int i = 0; i < removedCount; i++) {
20801                        deletePackageIfUnusedLPr(removedFromList.get(i));
20802                    }
20803                }
20804            }
20805        }
20806
20807        @Override
20808        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20809            synchronized (mPackages) {
20810                // If we do not support permission review, done.
20811                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20812                    return false;
20813                }
20814
20815                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20816                if (packageSetting == null) {
20817                    return false;
20818                }
20819
20820                // Permission review applies only to apps not supporting the new permission model.
20821                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20822                    return false;
20823                }
20824
20825                // Legacy apps have the permission and get user consent on launch.
20826                PermissionsState permissionsState = packageSetting.getPermissionsState();
20827                return permissionsState.isPermissionReviewRequired(userId);
20828            }
20829        }
20830
20831        @Override
20832        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20833            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20834        }
20835
20836        @Override
20837        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20838                int userId) {
20839            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20840        }
20841
20842        @Override
20843        public void setDeviceAndProfileOwnerPackages(
20844                int deviceOwnerUserId, String deviceOwnerPackage,
20845                SparseArray<String> profileOwnerPackages) {
20846            mProtectedPackages.setDeviceAndProfileOwnerPackages(
20847                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
20848        }
20849
20850        @Override
20851        public boolean isPackageDataProtected(int userId, String packageName) {
20852            return mProtectedPackages.isPackageDataProtected(userId, packageName);
20853        }
20854    }
20855
20856    @Override
20857    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20858        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20859        synchronized (mPackages) {
20860            final long identity = Binder.clearCallingIdentity();
20861            try {
20862                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20863                        packageNames, userId);
20864            } finally {
20865                Binder.restoreCallingIdentity(identity);
20866            }
20867        }
20868    }
20869
20870    private static void enforceSystemOrPhoneCaller(String tag) {
20871        int callingUid = Binder.getCallingUid();
20872        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20873            throw new SecurityException(
20874                    "Cannot call " + tag + " from UID " + callingUid);
20875        }
20876    }
20877
20878    boolean isHistoricalPackageUsageAvailable() {
20879        return mPackageUsage.isHistoricalPackageUsageAvailable();
20880    }
20881
20882    /**
20883     * Return a <b>copy</b> of the collection of packages known to the package manager.
20884     * @return A copy of the values of mPackages.
20885     */
20886    Collection<PackageParser.Package> getPackages() {
20887        synchronized (mPackages) {
20888            return new ArrayList<>(mPackages.values());
20889        }
20890    }
20891
20892    /**
20893     * Logs process start information (including base APK hash) to the security log.
20894     * @hide
20895     */
20896    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20897            String apkFile, int pid) {
20898        if (!SecurityLog.isLoggingEnabled()) {
20899            return;
20900        }
20901        Bundle data = new Bundle();
20902        data.putLong("startTimestamp", System.currentTimeMillis());
20903        data.putString("processName", processName);
20904        data.putInt("uid", uid);
20905        data.putString("seinfo", seinfo);
20906        data.putString("apkFile", apkFile);
20907        data.putInt("pid", pid);
20908        Message msg = mProcessLoggingHandler.obtainMessage(
20909                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20910        msg.setData(data);
20911        mProcessLoggingHandler.sendMessage(msg);
20912    }
20913
20914    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
20915        return mCompilerStats.getPackageStats(pkgName);
20916    }
20917
20918    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
20919        return getOrCreateCompilerPackageStats(pkg.packageName);
20920    }
20921
20922    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
20923        return mCompilerStats.getOrCreatePackageStats(pkgName);
20924    }
20925
20926    public void deleteCompilerPackageStats(String pkgName) {
20927        mCompilerStats.deletePackageStats(pkgName);
20928    }
20929}
20930