PackageManagerService.java revision 110a12dff13276baa12e8587449a1a7f3a318451
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.Process.PACKAGE_INFO_GID;
80import static android.os.Process.SYSTEM_UID;
81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
82import static android.system.OsConstants.O_CREAT;
83import static android.system.OsConstants.O_RDWR;
84
85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
89import static com.android.internal.util.ArrayUtils.appendInt;
90import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
101
102import android.Manifest;
103import android.annotation.NonNull;
104import android.annotation.Nullable;
105import android.app.ActivityManager;
106import android.app.ActivityManagerNative;
107import android.app.IActivityManager;
108import android.app.ResourcesManager;
109import android.app.admin.DevicePolicyManagerInternal;
110import android.app.admin.IDevicePolicyManager;
111import android.app.admin.SecurityLog;
112import android.app.backup.IBackupManager;
113import android.content.BroadcastReceiver;
114import android.content.ComponentName;
115import android.content.Context;
116import android.content.IIntentReceiver;
117import android.content.Intent;
118import android.content.IntentFilter;
119import android.content.IntentSender;
120import android.content.IntentSender.SendIntentException;
121import android.content.ServiceConnection;
122import android.content.pm.ActivityInfo;
123import android.content.pm.ApplicationInfo;
124import android.content.pm.AppsQueryHelper;
125import android.content.pm.ComponentInfo;
126import android.content.pm.EphemeralApplicationInfo;
127import android.content.pm.EphemeralResolveInfo;
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.security.KeyStore;
201import android.security.SystemKeyStore;
202import android.system.ErrnoException;
203import android.system.Os;
204import android.text.TextUtils;
205import android.text.format.DateUtils;
206import android.util.ArrayMap;
207import android.util.ArraySet;
208import android.util.AtomicFile;
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.BufferedInputStream;
268import java.io.BufferedOutputStream;
269import java.io.BufferedReader;
270import java.io.ByteArrayInputStream;
271import java.io.ByteArrayOutputStream;
272import java.io.File;
273import java.io.FileDescriptor;
274import java.io.FileInputStream;
275import java.io.FileNotFoundException;
276import java.io.FileOutputStream;
277import java.io.FileReader;
278import java.io.FilenameFilter;
279import java.io.IOException;
280import java.io.InputStream;
281import java.io.PrintWriter;
282import java.nio.charset.StandardCharsets;
283import java.security.DigestInputStream;
284import java.security.MessageDigest;
285import java.security.NoSuchAlgorithmException;
286import java.security.PublicKey;
287import java.security.cert.Certificate;
288import java.security.cert.CertificateEncodingException;
289import java.security.cert.CertificateException;
290import java.text.SimpleDateFormat;
291import java.util.ArrayList;
292import java.util.Arrays;
293import java.util.Collection;
294import java.util.Collections;
295import java.util.Comparator;
296import java.util.Date;
297import java.util.HashSet;
298import java.util.Iterator;
299import java.util.List;
300import java.util.Map;
301import java.util.Objects;
302import java.util.Set;
303import java.util.concurrent.CountDownLatch;
304import java.util.concurrent.TimeUnit;
305import java.util.concurrent.atomic.AtomicBoolean;
306import java.util.concurrent.atomic.AtomicInteger;
307import java.util.concurrent.atomic.AtomicLong;
308
309/**
310 * Keep track of all those APKs everywhere.
311 * <p>
312 * Internally there are two important locks:
313 * <ul>
314 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
315 * and other related state. It is a fine-grained lock that should only be held
316 * momentarily, as it's one of the most contended locks in the system.
317 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
318 * operations typically involve heavy lifting of application data on disk. Since
319 * {@code installd} is single-threaded, and it's operations can often be slow,
320 * this lock should never be acquired while already holding {@link #mPackages}.
321 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
322 * holding {@link #mInstallLock}.
323 * </ul>
324 * Many internal methods rely on the caller to hold the appropriate locks, and
325 * this contract is expressed through method name suffixes:
326 * <ul>
327 * <li>fooLI(): the caller must hold {@link #mInstallLock}
328 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
329 * being modified must be frozen
330 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
331 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
332 * </ul>
333 * <p>
334 * Because this class is very central to the platform's security; please run all
335 * CTS and unit tests whenever making modifications:
336 *
337 * <pre>
338 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
339 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests
340 * </pre>
341 */
342public class PackageManagerService extends IPackageManager.Stub {
343    static final String TAG = "PackageManager";
344    static final boolean DEBUG_SETTINGS = false;
345    static final boolean DEBUG_PREFERRED = false;
346    static final boolean DEBUG_UPGRADE = false;
347    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
348    private static final boolean DEBUG_BACKUP = false;
349    private static final boolean DEBUG_INSTALL = false;
350    private static final boolean DEBUG_REMOVE = false;
351    private static final boolean DEBUG_BROADCASTS = false;
352    private static final boolean DEBUG_SHOW_INFO = false;
353    private static final boolean DEBUG_PACKAGE_INFO = false;
354    private static final boolean DEBUG_INTENT_MATCHING = false;
355    private static final boolean DEBUG_PACKAGE_SCANNING = false;
356    private static final boolean DEBUG_VERIFY = false;
357    private static final boolean DEBUG_FILTERS = false;
358
359    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
360    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
361    // user, but by default initialize to this.
362    static final boolean DEBUG_DEXOPT = false;
363
364    private static final boolean DEBUG_ABI_SELECTION = false;
365    private static final boolean DEBUG_EPHEMERAL = false;
366    private static final boolean DEBUG_TRIAGED_MISSING = false;
367    private static final boolean DEBUG_APP_DATA = false;
368
369    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
370
371    private static final boolean DISABLE_EPHEMERAL_APPS = true;
372
373    private static final int RADIO_UID = Process.PHONE_UID;
374    private static final int LOG_UID = Process.LOG_UID;
375    private static final int NFC_UID = Process.NFC_UID;
376    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
377    private static final int SHELL_UID = Process.SHELL_UID;
378
379    // Cap the size of permission trees that 3rd party apps can define
380    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
381
382    // Suffix used during package installation when copying/moving
383    // package apks to install directory.
384    private static final String INSTALL_PACKAGE_SUFFIX = "-";
385
386    static final int SCAN_NO_DEX = 1<<1;
387    static final int SCAN_FORCE_DEX = 1<<2;
388    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
389    static final int SCAN_NEW_INSTALL = 1<<4;
390    static final int SCAN_NO_PATHS = 1<<5;
391    static final int SCAN_UPDATE_TIME = 1<<6;
392    static final int SCAN_DEFER_DEX = 1<<7;
393    static final int SCAN_BOOTING = 1<<8;
394    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
395    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
396    static final int SCAN_REPLACING = 1<<11;
397    static final int SCAN_REQUIRE_KNOWN = 1<<12;
398    static final int SCAN_MOVE = 1<<13;
399    static final int SCAN_INITIAL = 1<<14;
400    static final int SCAN_CHECK_ONLY = 1<<15;
401    static final int SCAN_DONT_KILL_APP = 1<<17;
402    static final int SCAN_IGNORE_FROZEN = 1<<18;
403
404    static final int REMOVE_CHATTY = 1<<16;
405
406    private static final int[] EMPTY_INT_ARRAY = new int[0];
407
408    /**
409     * Timeout (in milliseconds) after which the watchdog should declare that
410     * our handler thread is wedged.  The usual default for such things is one
411     * minute but we sometimes do very lengthy I/O operations on this thread,
412     * such as installing multi-gigabyte applications, so ours needs to be longer.
413     */
414    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
415
416    /**
417     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
418     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
419     * settings entry if available, otherwise we use the hardcoded default.  If it's been
420     * more than this long since the last fstrim, we force one during the boot sequence.
421     *
422     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
423     * one gets run at the next available charging+idle time.  This final mandatory
424     * no-fstrim check kicks in only of the other scheduling criteria is never met.
425     */
426    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
427
428    /**
429     * Whether verification is enabled by default.
430     */
431    private static final boolean DEFAULT_VERIFY_ENABLE = true;
432
433    /**
434     * The default maximum time to wait for the verification agent to return in
435     * milliseconds.
436     */
437    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
438
439    /**
440     * The default response for package verification timeout.
441     *
442     * This can be either PackageManager.VERIFICATION_ALLOW or
443     * PackageManager.VERIFICATION_REJECT.
444     */
445    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
446
447    static final String PLATFORM_PACKAGE_NAME = "android";
448
449    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
450
451    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
452            DEFAULT_CONTAINER_PACKAGE,
453            "com.android.defcontainer.DefaultContainerService");
454
455    private static final String KILL_APP_REASON_GIDS_CHANGED =
456            "permission grant or revoke changed gids";
457
458    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
459            "permissions revoked";
460
461    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
462
463    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
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    boolean mRestoredSettings;
626
627    // System configuration read by SystemConfig.
628    final int[] mGlobalGids;
629    final SparseArray<ArraySet<String>> mSystemPermissions;
630    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
631
632    // If mac_permissions.xml was found for seinfo labeling.
633    boolean mFoundPolicyFile;
634
635    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
636
637    public static final class SharedLibraryEntry {
638        public final String path;
639        public final String apk;
640
641        SharedLibraryEntry(String _path, String _apk) {
642            path = _path;
643            apk = _apk;
644        }
645    }
646
647    // Currently known shared libraries.
648    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
649            new ArrayMap<String, SharedLibraryEntry>();
650
651    // All available activities, for your resolving pleasure.
652    final ActivityIntentResolver mActivities =
653            new ActivityIntentResolver();
654
655    // All available receivers, for your resolving pleasure.
656    final ActivityIntentResolver mReceivers =
657            new ActivityIntentResolver();
658
659    // All available services, for your resolving pleasure.
660    final ServiceIntentResolver mServices = new ServiceIntentResolver();
661
662    // All available providers, for your resolving pleasure.
663    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
664
665    // Mapping from provider base names (first directory in content URI codePath)
666    // to the provider information.
667    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
668            new ArrayMap<String, PackageParser.Provider>();
669
670    // Mapping from instrumentation class names to info about them.
671    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
672            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
673
674    // Mapping from permission names to info about them.
675    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
676            new ArrayMap<String, PackageParser.PermissionGroup>();
677
678    // Packages whose data we have transfered into another package, thus
679    // should no longer exist.
680    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
681
682    // Broadcast actions that are only available to the system.
683    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
684
685    /** List of packages waiting for verification. */
686    final SparseArray<PackageVerificationState> mPendingVerification
687            = new SparseArray<PackageVerificationState>();
688
689    /** Set of packages associated with each app op permission. */
690    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
691
692    final PackageInstallerService mInstallerService;
693
694    private final PackageDexOptimizer mPackageDexOptimizer;
695
696    private AtomicInteger mNextMoveId = new AtomicInteger();
697    private final MoveCallbacks mMoveCallbacks;
698
699    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
700
701    // Cache of users who need badging.
702    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
703
704    /** Token for keys in mPendingVerification. */
705    private int mPendingVerificationToken = 0;
706
707    volatile boolean mSystemReady;
708    volatile boolean mSafeMode;
709    volatile boolean mHasSystemUidErrors;
710
711    ApplicationInfo mAndroidApplication;
712    final ActivityInfo mResolveActivity = new ActivityInfo();
713    final ResolveInfo mResolveInfo = new ResolveInfo();
714    ComponentName mResolveComponentName;
715    PackageParser.Package mPlatformPackage;
716    ComponentName mCustomResolverComponentName;
717
718    boolean mResolverReplaced = false;
719
720    private final @Nullable ComponentName mIntentFilterVerifierComponent;
721    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
722
723    private int mIntentFilterVerificationToken = 0;
724
725    /** Component that knows whether or not an ephemeral application exists */
726    final ComponentName mEphemeralResolverComponent;
727    /** The service connection to the ephemeral resolver */
728    final EphemeralResolverConnection mEphemeralResolverConnection;
729
730    /** Component used to install ephemeral applications */
731    final ComponentName mEphemeralInstallerComponent;
732    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
733    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
734
735    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
736            = new SparseArray<IntentFilterVerificationState>();
737
738    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
739            new DefaultPermissionGrantPolicy(this);
740
741    // List of packages names to keep cached, even if they are uninstalled for all users
742    private List<String> mKeepUninstalledPackages;
743
744    private UserManagerInternal mUserManagerInternal;
745
746    private static class IFVerificationParams {
747        PackageParser.Package pkg;
748        boolean replacing;
749        int userId;
750        int verifierUid;
751
752        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
753                int _userId, int _verifierUid) {
754            pkg = _pkg;
755            replacing = _replacing;
756            userId = _userId;
757            replacing = _replacing;
758            verifierUid = _verifierUid;
759        }
760    }
761
762    private interface IntentFilterVerifier<T extends IntentFilter> {
763        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
764                                               T filter, String packageName);
765        void startVerifications(int userId);
766        void receiveVerificationResponse(int verificationId);
767    }
768
769    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
770        private Context mContext;
771        private ComponentName mIntentFilterVerifierComponent;
772        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
773
774        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
775            mContext = context;
776            mIntentFilterVerifierComponent = verifierComponent;
777        }
778
779        private String getDefaultScheme() {
780            return IntentFilter.SCHEME_HTTPS;
781        }
782
783        @Override
784        public void startVerifications(int userId) {
785            // Launch verifications requests
786            int count = mCurrentIntentFilterVerifications.size();
787            for (int n=0; n<count; n++) {
788                int verificationId = mCurrentIntentFilterVerifications.get(n);
789                final IntentFilterVerificationState ivs =
790                        mIntentFilterVerificationStates.get(verificationId);
791
792                String packageName = ivs.getPackageName();
793
794                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
795                final int filterCount = filters.size();
796                ArraySet<String> domainsSet = new ArraySet<>();
797                for (int m=0; m<filterCount; m++) {
798                    PackageParser.ActivityIntentInfo filter = filters.get(m);
799                    domainsSet.addAll(filter.getHostsList());
800                }
801                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
802                synchronized (mPackages) {
803                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
804                            packageName, domainsList) != null) {
805                        scheduleWriteSettingsLocked();
806                    }
807                }
808                sendVerificationRequest(userId, verificationId, ivs);
809            }
810            mCurrentIntentFilterVerifications.clear();
811        }
812
813        private void sendVerificationRequest(int userId, int verificationId,
814                IntentFilterVerificationState ivs) {
815
816            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
817            verificationIntent.putExtra(
818                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
819                    verificationId);
820            verificationIntent.putExtra(
821                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
822                    getDefaultScheme());
823            verificationIntent.putExtra(
824                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
825                    ivs.getHostsString());
826            verificationIntent.putExtra(
827                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
828                    ivs.getPackageName());
829            verificationIntent.setComponent(mIntentFilterVerifierComponent);
830            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
831
832            UserHandle user = new UserHandle(userId);
833            mContext.sendBroadcastAsUser(verificationIntent, user);
834            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
835                    "Sending IntentFilter verification broadcast");
836        }
837
838        public void receiveVerificationResponse(int verificationId) {
839            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
840
841            final boolean verified = ivs.isVerified();
842
843            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
844            final int count = filters.size();
845            if (DEBUG_DOMAIN_VERIFICATION) {
846                Slog.i(TAG, "Received verification response " + verificationId
847                        + " for " + count + " filters, verified=" + verified);
848            }
849            for (int n=0; n<count; n++) {
850                PackageParser.ActivityIntentInfo filter = filters.get(n);
851                filter.setVerified(verified);
852
853                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
854                        + " verified with result:" + verified + " and hosts:"
855                        + ivs.getHostsString());
856            }
857
858            mIntentFilterVerificationStates.remove(verificationId);
859
860            final String packageName = ivs.getPackageName();
861            IntentFilterVerificationInfo ivi = null;
862
863            synchronized (mPackages) {
864                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
865            }
866            if (ivi == null) {
867                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
868                        + verificationId + " packageName:" + packageName);
869                return;
870            }
871            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
872                    "Updating IntentFilterVerificationInfo for package " + packageName
873                            +" verificationId:" + verificationId);
874
875            synchronized (mPackages) {
876                if (verified) {
877                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
878                } else {
879                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
880                }
881                scheduleWriteSettingsLocked();
882
883                final int userId = ivs.getUserId();
884                if (userId != UserHandle.USER_ALL) {
885                    final int userStatus =
886                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
887
888                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
889                    boolean needUpdate = false;
890
891                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
892                    // already been set by the User thru the Disambiguation dialog
893                    switch (userStatus) {
894                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
895                            if (verified) {
896                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
897                            } else {
898                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
899                            }
900                            needUpdate = true;
901                            break;
902
903                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
904                            if (verified) {
905                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
906                                needUpdate = true;
907                            }
908                            break;
909
910                        default:
911                            // Nothing to do
912                    }
913
914                    if (needUpdate) {
915                        mSettings.updateIntentFilterVerificationStatusLPw(
916                                packageName, updatedStatus, userId);
917                        scheduleWritePackageRestrictionsLocked(userId);
918                    }
919                }
920            }
921        }
922
923        @Override
924        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
925                    ActivityIntentInfo filter, String packageName) {
926            if (!hasValidDomains(filter)) {
927                return false;
928            }
929            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
930            if (ivs == null) {
931                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
932                        packageName);
933            }
934            if (DEBUG_DOMAIN_VERIFICATION) {
935                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
936            }
937            ivs.addFilter(filter);
938            return true;
939        }
940
941        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
942                int userId, int verificationId, String packageName) {
943            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
944                    verifierUid, userId, packageName);
945            ivs.setPendingState();
946            synchronized (mPackages) {
947                mIntentFilterVerificationStates.append(verificationId, ivs);
948                mCurrentIntentFilterVerifications.add(verificationId);
949            }
950            return ivs;
951        }
952    }
953
954    private static boolean hasValidDomains(ActivityIntentInfo filter) {
955        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
956                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
957                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
958    }
959
960    // Set of pending broadcasts for aggregating enable/disable of components.
961    static class PendingPackageBroadcasts {
962        // for each user id, a map of <package name -> components within that package>
963        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
964
965        public PendingPackageBroadcasts() {
966            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
967        }
968
969        public ArrayList<String> get(int userId, String packageName) {
970            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
971            return packages.get(packageName);
972        }
973
974        public void put(int userId, String packageName, ArrayList<String> components) {
975            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
976            packages.put(packageName, components);
977        }
978
979        public void remove(int userId, String packageName) {
980            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
981            if (packages != null) {
982                packages.remove(packageName);
983            }
984        }
985
986        public void remove(int userId) {
987            mUidMap.remove(userId);
988        }
989
990        public int userIdCount() {
991            return mUidMap.size();
992        }
993
994        public int userIdAt(int n) {
995            return mUidMap.keyAt(n);
996        }
997
998        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
999            return mUidMap.get(userId);
1000        }
1001
1002        public int size() {
1003            // total number of pending broadcast entries across all userIds
1004            int num = 0;
1005            for (int i = 0; i< mUidMap.size(); i++) {
1006                num += mUidMap.valueAt(i).size();
1007            }
1008            return num;
1009        }
1010
1011        public void clear() {
1012            mUidMap.clear();
1013        }
1014
1015        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1016            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1017            if (map == null) {
1018                map = new ArrayMap<String, ArrayList<String>>();
1019                mUidMap.put(userId, map);
1020            }
1021            return map;
1022        }
1023    }
1024    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1025
1026    // Service Connection to remote media container service to copy
1027    // package uri's from external media onto secure containers
1028    // or internal storage.
1029    private IMediaContainerService mContainerService = null;
1030
1031    static final int SEND_PENDING_BROADCAST = 1;
1032    static final int MCS_BOUND = 3;
1033    static final int END_COPY = 4;
1034    static final int INIT_COPY = 5;
1035    static final int MCS_UNBIND = 6;
1036    static final int START_CLEANING_PACKAGE = 7;
1037    static final int FIND_INSTALL_LOC = 8;
1038    static final int POST_INSTALL = 9;
1039    static final int MCS_RECONNECT = 10;
1040    static final int MCS_GIVE_UP = 11;
1041    static final int UPDATED_MEDIA_STATUS = 12;
1042    static final int WRITE_SETTINGS = 13;
1043    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1044    static final int PACKAGE_VERIFIED = 15;
1045    static final int CHECK_PENDING_VERIFICATION = 16;
1046    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1047    static final int INTENT_FILTER_VERIFIED = 18;
1048    static final int WRITE_PACKAGE_LIST = 19;
1049
1050    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1051
1052    // Delay time in millisecs
1053    static final int BROADCAST_DELAY = 10 * 1000;
1054
1055    static UserManagerService sUserManager;
1056
1057    // Stores a list of users whose package restrictions file needs to be updated
1058    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1059
1060    final private DefaultContainerConnection mDefContainerConn =
1061            new DefaultContainerConnection();
1062    class DefaultContainerConnection implements ServiceConnection {
1063        public void onServiceConnected(ComponentName name, IBinder service) {
1064            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1065            IMediaContainerService imcs =
1066                IMediaContainerService.Stub.asInterface(service);
1067            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1068        }
1069
1070        public void onServiceDisconnected(ComponentName name) {
1071            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1072        }
1073    }
1074
1075    // Recordkeeping of restore-after-install operations that are currently in flight
1076    // between the Package Manager and the Backup Manager
1077    static class PostInstallData {
1078        public InstallArgs args;
1079        public PackageInstalledInfo res;
1080
1081        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1082            args = _a;
1083            res = _r;
1084        }
1085    }
1086
1087    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1088    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1089
1090    // XML tags for backup/restore of various bits of state
1091    private static final String TAG_PREFERRED_BACKUP = "pa";
1092    private static final String TAG_DEFAULT_APPS = "da";
1093    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1094
1095    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1096    private static final String TAG_ALL_GRANTS = "rt-grants";
1097    private static final String TAG_GRANT = "grant";
1098    private static final String ATTR_PACKAGE_NAME = "pkg";
1099
1100    private static final String TAG_PERMISSION = "perm";
1101    private static final String ATTR_PERMISSION_NAME = "name";
1102    private static final String ATTR_IS_GRANTED = "g";
1103    private static final String ATTR_USER_SET = "set";
1104    private static final String ATTR_USER_FIXED = "fixed";
1105    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1106
1107    // System/policy permission grants are not backed up
1108    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1109            FLAG_PERMISSION_POLICY_FIXED
1110            | FLAG_PERMISSION_SYSTEM_FIXED
1111            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1112
1113    // And we back up these user-adjusted states
1114    private static final int USER_RUNTIME_GRANT_MASK =
1115            FLAG_PERMISSION_USER_SET
1116            | FLAG_PERMISSION_USER_FIXED
1117            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1118
1119    final @Nullable String mRequiredVerifierPackage;
1120    final @NonNull String mRequiredInstallerPackage;
1121    final @Nullable String mSetupWizardPackage;
1122    final @NonNull String mServicesSystemSharedLibraryPackageName;
1123    final @NonNull String mSharedSystemSharedLibraryPackageName;
1124
1125    private final PackageUsage mPackageUsage = new PackageUsage();
1126
1127    private class PackageUsage {
1128        private static final int WRITE_INTERVAL
1129            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1130
1131        private final Object mFileLock = new Object();
1132        private final AtomicLong mLastWritten = new AtomicLong(0);
1133        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1134
1135        private boolean mIsHistoricalPackageUsageAvailable = true;
1136
1137        boolean isHistoricalPackageUsageAvailable() {
1138            return mIsHistoricalPackageUsageAvailable;
1139        }
1140
1141        void write(boolean force) {
1142            if (force) {
1143                writeInternal();
1144                return;
1145            }
1146            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1147                && !DEBUG_DEXOPT) {
1148                return;
1149            }
1150            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1151                new Thread("PackageUsage_DiskWriter") {
1152                    @Override
1153                    public void run() {
1154                        try {
1155                            writeInternal();
1156                        } finally {
1157                            mBackgroundWriteRunning.set(false);
1158                        }
1159                    }
1160                }.start();
1161            }
1162        }
1163
1164        private void writeInternal() {
1165            synchronized (mPackages) {
1166                synchronized (mFileLock) {
1167                    AtomicFile file = getFile();
1168                    FileOutputStream f = null;
1169                    try {
1170                        f = file.startWrite();
1171                        BufferedOutputStream out = new BufferedOutputStream(f);
1172                        FileUtils.setPermissions(file.getBaseFile().getPath(),
1173                                0640, SYSTEM_UID, PACKAGE_INFO_GID);
1174                        StringBuilder sb = new StringBuilder();
1175
1176                        sb.append(USAGE_FILE_MAGIC_VERSION_1);
1177                        sb.append('\n');
1178                        out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1179
1180                        for (PackageParser.Package pkg : mPackages.values()) {
1181                            if (pkg.getLatestPackageUseTimeInMills() == 0L) {
1182                                continue;
1183                            }
1184                            sb.setLength(0);
1185                            sb.append(pkg.packageName);
1186                            for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) {
1187                                sb.append(' ');
1188                                sb.append(usageTimeInMillis);
1189                            }
1190                            sb.append('\n');
1191                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1192                        }
1193                        out.flush();
1194                        file.finishWrite(f);
1195                    } catch (IOException e) {
1196                        if (f != null) {
1197                            file.failWrite(f);
1198                        }
1199                        Log.e(TAG, "Failed to write package usage times", e);
1200                    }
1201                }
1202            }
1203            mLastWritten.set(SystemClock.elapsedRealtime());
1204        }
1205
1206        void readLP() {
1207            synchronized (mFileLock) {
1208                AtomicFile file = getFile();
1209                BufferedInputStream in = null;
1210                try {
1211                    in = new BufferedInputStream(file.openRead());
1212                    StringBuffer sb = new StringBuffer();
1213
1214                    String firstLine = readLine(in, sb);
1215                    if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) {
1216                        readVersion1LP(in, sb);
1217                    } else {
1218                        readVersion0LP(in, sb, firstLine);
1219                    }
1220                } catch (FileNotFoundException expected) {
1221                    mIsHistoricalPackageUsageAvailable = false;
1222                } catch (IOException e) {
1223                    Log.w(TAG, "Failed to read package usage times", e);
1224                } finally {
1225                    IoUtils.closeQuietly(in);
1226                }
1227            }
1228            mLastWritten.set(SystemClock.elapsedRealtime());
1229        }
1230
1231        private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine)
1232                throws IOException {
1233            // Initial version of the file had no version number and stored one
1234            // package-timestamp pair per line.
1235            // Note that the first line has already been read from the InputStream.
1236            for (String line = firstLine; line != null; line = readLine(in, sb)) {
1237                String[] tokens = line.split(" ");
1238                if (tokens.length != 2) {
1239                    throw new IOException("Failed to parse " + line +
1240                            " as package-timestamp pair.");
1241                }
1242
1243                String packageName = tokens[0];
1244                PackageParser.Package pkg = mPackages.get(packageName);
1245                if (pkg == null) {
1246                    continue;
1247                }
1248
1249                long timestamp = parseAsLong(tokens[1]);
1250                for (int reason = 0;
1251                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1252                        reason++) {
1253                    pkg.mLastPackageUsageTimeInMills[reason] = timestamp;
1254                }
1255            }
1256        }
1257
1258        private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException {
1259            // Version 1 of the file started with the corresponding version
1260            // number and then stored a package name and eight timestamps per line.
1261            String line;
1262            while ((line = readLine(in, sb)) != null) {
1263                String[] tokens = line.split(" ");
1264                if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) {
1265                    throw new IOException("Failed to parse " + line + " as a timestamp array.");
1266                }
1267
1268                String packageName = tokens[0];
1269                PackageParser.Package pkg = mPackages.get(packageName);
1270                if (pkg == null) {
1271                    continue;
1272                }
1273
1274                for (int reason = 0;
1275                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1276                        reason++) {
1277                    pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]);
1278                }
1279            }
1280        }
1281
1282        private long parseAsLong(String token) throws IOException {
1283            try {
1284                return Long.parseLong(token);
1285            } catch (NumberFormatException e) {
1286                throw new IOException("Failed to parse " + token + " as a long.", e);
1287            }
1288        }
1289
1290        private String readLine(InputStream in, StringBuffer sb) throws IOException {
1291            return readToken(in, sb, '\n');
1292        }
1293
1294        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1295                throws IOException {
1296            sb.setLength(0);
1297            while (true) {
1298                int ch = in.read();
1299                if (ch == -1) {
1300                    if (sb.length() == 0) {
1301                        return null;
1302                    }
1303                    throw new IOException("Unexpected EOF");
1304                }
1305                if (ch == endOfToken) {
1306                    return sb.toString();
1307                }
1308                sb.append((char)ch);
1309            }
1310        }
1311
1312        private AtomicFile getFile() {
1313            File dataDir = Environment.getDataDirectory();
1314            File systemDir = new File(dataDir, "system");
1315            File fname = new File(systemDir, "package-usage.list");
1316            return new AtomicFile(fname);
1317        }
1318
1319        private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_";
1320        private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1";
1321    }
1322
1323    class PackageHandler extends Handler {
1324        private boolean mBound = false;
1325        final ArrayList<HandlerParams> mPendingInstalls =
1326            new ArrayList<HandlerParams>();
1327
1328        private boolean connectToService() {
1329            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1330                    " DefaultContainerService");
1331            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1332            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1333            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1334                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1335                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1336                mBound = true;
1337                return true;
1338            }
1339            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1340            return false;
1341        }
1342
1343        private void disconnectService() {
1344            mContainerService = null;
1345            mBound = false;
1346            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1347            mContext.unbindService(mDefContainerConn);
1348            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1349        }
1350
1351        PackageHandler(Looper looper) {
1352            super(looper);
1353        }
1354
1355        public void handleMessage(Message msg) {
1356            try {
1357                doHandleMessage(msg);
1358            } finally {
1359                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1360            }
1361        }
1362
1363        void doHandleMessage(Message msg) {
1364            switch (msg.what) {
1365                case INIT_COPY: {
1366                    HandlerParams params = (HandlerParams) msg.obj;
1367                    int idx = mPendingInstalls.size();
1368                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1369                    // If a bind was already initiated we dont really
1370                    // need to do anything. The pending install
1371                    // will be processed later on.
1372                    if (!mBound) {
1373                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1374                                System.identityHashCode(mHandler));
1375                        // If this is the only one pending we might
1376                        // have to bind to the service again.
1377                        if (!connectToService()) {
1378                            Slog.e(TAG, "Failed to bind to media container service");
1379                            params.serviceError();
1380                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1381                                    System.identityHashCode(mHandler));
1382                            if (params.traceMethod != null) {
1383                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1384                                        params.traceCookie);
1385                            }
1386                            return;
1387                        } else {
1388                            // Once we bind to the service, the first
1389                            // pending request will be processed.
1390                            mPendingInstalls.add(idx, params);
1391                        }
1392                    } else {
1393                        mPendingInstalls.add(idx, params);
1394                        // Already bound to the service. Just make
1395                        // sure we trigger off processing the first request.
1396                        if (idx == 0) {
1397                            mHandler.sendEmptyMessage(MCS_BOUND);
1398                        }
1399                    }
1400                    break;
1401                }
1402                case MCS_BOUND: {
1403                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1404                    if (msg.obj != null) {
1405                        mContainerService = (IMediaContainerService) msg.obj;
1406                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1407                                System.identityHashCode(mHandler));
1408                    }
1409                    if (mContainerService == null) {
1410                        if (!mBound) {
1411                            // Something seriously wrong since we are not bound and we are not
1412                            // waiting for connection. Bail out.
1413                            Slog.e(TAG, "Cannot bind to media container service");
1414                            for (HandlerParams params : mPendingInstalls) {
1415                                // Indicate service bind error
1416                                params.serviceError();
1417                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1418                                        System.identityHashCode(params));
1419                                if (params.traceMethod != null) {
1420                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1421                                            params.traceMethod, params.traceCookie);
1422                                }
1423                                return;
1424                            }
1425                            mPendingInstalls.clear();
1426                        } else {
1427                            Slog.w(TAG, "Waiting to connect to media container service");
1428                        }
1429                    } else if (mPendingInstalls.size() > 0) {
1430                        HandlerParams params = mPendingInstalls.get(0);
1431                        if (params != null) {
1432                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1433                                    System.identityHashCode(params));
1434                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1435                            if (params.startCopy()) {
1436                                // We are done...  look for more work or to
1437                                // go idle.
1438                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1439                                        "Checking for more work or unbind...");
1440                                // Delete pending install
1441                                if (mPendingInstalls.size() > 0) {
1442                                    mPendingInstalls.remove(0);
1443                                }
1444                                if (mPendingInstalls.size() == 0) {
1445                                    if (mBound) {
1446                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1447                                                "Posting delayed MCS_UNBIND");
1448                                        removeMessages(MCS_UNBIND);
1449                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1450                                        // Unbind after a little delay, to avoid
1451                                        // continual thrashing.
1452                                        sendMessageDelayed(ubmsg, 10000);
1453                                    }
1454                                } else {
1455                                    // There are more pending requests in queue.
1456                                    // Just post MCS_BOUND message to trigger processing
1457                                    // of next pending install.
1458                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1459                                            "Posting MCS_BOUND for next work");
1460                                    mHandler.sendEmptyMessage(MCS_BOUND);
1461                                }
1462                            }
1463                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1464                        }
1465                    } else {
1466                        // Should never happen ideally.
1467                        Slog.w(TAG, "Empty queue");
1468                    }
1469                    break;
1470                }
1471                case MCS_RECONNECT: {
1472                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1473                    if (mPendingInstalls.size() > 0) {
1474                        if (mBound) {
1475                            disconnectService();
1476                        }
1477                        if (!connectToService()) {
1478                            Slog.e(TAG, "Failed to bind to media container service");
1479                            for (HandlerParams params : mPendingInstalls) {
1480                                // Indicate service bind error
1481                                params.serviceError();
1482                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1483                                        System.identityHashCode(params));
1484                            }
1485                            mPendingInstalls.clear();
1486                        }
1487                    }
1488                    break;
1489                }
1490                case MCS_UNBIND: {
1491                    // If there is no actual work left, then time to unbind.
1492                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1493
1494                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1495                        if (mBound) {
1496                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1497
1498                            disconnectService();
1499                        }
1500                    } else if (mPendingInstalls.size() > 0) {
1501                        // There are more pending requests in queue.
1502                        // Just post MCS_BOUND message to trigger processing
1503                        // of next pending install.
1504                        mHandler.sendEmptyMessage(MCS_BOUND);
1505                    }
1506
1507                    break;
1508                }
1509                case MCS_GIVE_UP: {
1510                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1511                    HandlerParams params = mPendingInstalls.remove(0);
1512                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1513                            System.identityHashCode(params));
1514                    break;
1515                }
1516                case SEND_PENDING_BROADCAST: {
1517                    String packages[];
1518                    ArrayList<String> components[];
1519                    int size = 0;
1520                    int uids[];
1521                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1522                    synchronized (mPackages) {
1523                        if (mPendingBroadcasts == null) {
1524                            return;
1525                        }
1526                        size = mPendingBroadcasts.size();
1527                        if (size <= 0) {
1528                            // Nothing to be done. Just return
1529                            return;
1530                        }
1531                        packages = new String[size];
1532                        components = new ArrayList[size];
1533                        uids = new int[size];
1534                        int i = 0;  // filling out the above arrays
1535
1536                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1537                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1538                            Iterator<Map.Entry<String, ArrayList<String>>> it
1539                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1540                                            .entrySet().iterator();
1541                            while (it.hasNext() && i < size) {
1542                                Map.Entry<String, ArrayList<String>> ent = it.next();
1543                                packages[i] = ent.getKey();
1544                                components[i] = ent.getValue();
1545                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1546                                uids[i] = (ps != null)
1547                                        ? UserHandle.getUid(packageUserId, ps.appId)
1548                                        : -1;
1549                                i++;
1550                            }
1551                        }
1552                        size = i;
1553                        mPendingBroadcasts.clear();
1554                    }
1555                    // Send broadcasts
1556                    for (int i = 0; i < size; i++) {
1557                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1558                    }
1559                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1560                    break;
1561                }
1562                case START_CLEANING_PACKAGE: {
1563                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1564                    final String packageName = (String)msg.obj;
1565                    final int userId = msg.arg1;
1566                    final boolean andCode = msg.arg2 != 0;
1567                    synchronized (mPackages) {
1568                        if (userId == UserHandle.USER_ALL) {
1569                            int[] users = sUserManager.getUserIds();
1570                            for (int user : users) {
1571                                mSettings.addPackageToCleanLPw(
1572                                        new PackageCleanItem(user, packageName, andCode));
1573                            }
1574                        } else {
1575                            mSettings.addPackageToCleanLPw(
1576                                    new PackageCleanItem(userId, packageName, andCode));
1577                        }
1578                    }
1579                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1580                    startCleaningPackages();
1581                } break;
1582                case POST_INSTALL: {
1583                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1584
1585                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1586                    final boolean didRestore = (msg.arg2 != 0);
1587                    mRunningInstalls.delete(msg.arg1);
1588
1589                    if (data != null) {
1590                        InstallArgs args = data.args;
1591                        PackageInstalledInfo parentRes = data.res;
1592
1593                        final boolean grantPermissions = (args.installFlags
1594                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1595                        final boolean killApp = (args.installFlags
1596                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1597                        final String[] grantedPermissions = args.installGrantPermissions;
1598
1599                        // Handle the parent package
1600                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1601                                grantedPermissions, didRestore, args.installerPackageName,
1602                                args.observer);
1603
1604                        // Handle the child packages
1605                        final int childCount = (parentRes.addedChildPackages != null)
1606                                ? parentRes.addedChildPackages.size() : 0;
1607                        for (int i = 0; i < childCount; i++) {
1608                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1609                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1610                                    grantedPermissions, false, args.installerPackageName,
1611                                    args.observer);
1612                        }
1613
1614                        // Log tracing if needed
1615                        if (args.traceMethod != null) {
1616                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1617                                    args.traceCookie);
1618                        }
1619                    } else {
1620                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1621                    }
1622
1623                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1624                } break;
1625                case UPDATED_MEDIA_STATUS: {
1626                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1627                    boolean reportStatus = msg.arg1 == 1;
1628                    boolean doGc = msg.arg2 == 1;
1629                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1630                    if (doGc) {
1631                        // Force a gc to clear up stale containers.
1632                        Runtime.getRuntime().gc();
1633                    }
1634                    if (msg.obj != null) {
1635                        @SuppressWarnings("unchecked")
1636                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1637                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1638                        // Unload containers
1639                        unloadAllContainers(args);
1640                    }
1641                    if (reportStatus) {
1642                        try {
1643                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1644                            PackageHelper.getMountService().finishMediaUpdate();
1645                        } catch (RemoteException e) {
1646                            Log.e(TAG, "MountService not running?");
1647                        }
1648                    }
1649                } break;
1650                case WRITE_SETTINGS: {
1651                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1652                    synchronized (mPackages) {
1653                        removeMessages(WRITE_SETTINGS);
1654                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1655                        mSettings.writeLPr();
1656                        mDirtyUsers.clear();
1657                    }
1658                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1659                } break;
1660                case WRITE_PACKAGE_RESTRICTIONS: {
1661                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1662                    synchronized (mPackages) {
1663                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1664                        for (int userId : mDirtyUsers) {
1665                            mSettings.writePackageRestrictionsLPr(userId);
1666                        }
1667                        mDirtyUsers.clear();
1668                    }
1669                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1670                } break;
1671                case WRITE_PACKAGE_LIST: {
1672                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1673                    synchronized (mPackages) {
1674                        removeMessages(WRITE_PACKAGE_LIST);
1675                        mSettings.writePackageListLPr(msg.arg1);
1676                    }
1677                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1678                } break;
1679                case CHECK_PENDING_VERIFICATION: {
1680                    final int verificationId = msg.arg1;
1681                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1682
1683                    if ((state != null) && !state.timeoutExtended()) {
1684                        final InstallArgs args = state.getInstallArgs();
1685                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1686
1687                        Slog.i(TAG, "Verification timed out for " + originUri);
1688                        mPendingVerification.remove(verificationId);
1689
1690                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1691
1692                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1693                            Slog.i(TAG, "Continuing with installation of " + originUri);
1694                            state.setVerifierResponse(Binder.getCallingUid(),
1695                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1696                            broadcastPackageVerified(verificationId, originUri,
1697                                    PackageManager.VERIFICATION_ALLOW,
1698                                    state.getInstallArgs().getUser());
1699                            try {
1700                                ret = args.copyApk(mContainerService, true);
1701                            } catch (RemoteException e) {
1702                                Slog.e(TAG, "Could not contact the ContainerService");
1703                            }
1704                        } else {
1705                            broadcastPackageVerified(verificationId, originUri,
1706                                    PackageManager.VERIFICATION_REJECT,
1707                                    state.getInstallArgs().getUser());
1708                        }
1709
1710                        Trace.asyncTraceEnd(
1711                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1712
1713                        processPendingInstall(args, ret);
1714                        mHandler.sendEmptyMessage(MCS_UNBIND);
1715                    }
1716                    break;
1717                }
1718                case PACKAGE_VERIFIED: {
1719                    final int verificationId = msg.arg1;
1720
1721                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1722                    if (state == null) {
1723                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1724                        break;
1725                    }
1726
1727                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1728
1729                    state.setVerifierResponse(response.callerUid, response.code);
1730
1731                    if (state.isVerificationComplete()) {
1732                        mPendingVerification.remove(verificationId);
1733
1734                        final InstallArgs args = state.getInstallArgs();
1735                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1736
1737                        int ret;
1738                        if (state.isInstallAllowed()) {
1739                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1740                            broadcastPackageVerified(verificationId, originUri,
1741                                    response.code, state.getInstallArgs().getUser());
1742                            try {
1743                                ret = args.copyApk(mContainerService, true);
1744                            } catch (RemoteException e) {
1745                                Slog.e(TAG, "Could not contact the ContainerService");
1746                            }
1747                        } else {
1748                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1749                        }
1750
1751                        Trace.asyncTraceEnd(
1752                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1753
1754                        processPendingInstall(args, ret);
1755                        mHandler.sendEmptyMessage(MCS_UNBIND);
1756                    }
1757
1758                    break;
1759                }
1760                case START_INTENT_FILTER_VERIFICATIONS: {
1761                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1762                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1763                            params.replacing, params.pkg);
1764                    break;
1765                }
1766                case INTENT_FILTER_VERIFIED: {
1767                    final int verificationId = msg.arg1;
1768
1769                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1770                            verificationId);
1771                    if (state == null) {
1772                        Slog.w(TAG, "Invalid IntentFilter verification token "
1773                                + verificationId + " received");
1774                        break;
1775                    }
1776
1777                    final int userId = state.getUserId();
1778
1779                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1780                            "Processing IntentFilter verification with token:"
1781                            + verificationId + " and userId:" + userId);
1782
1783                    final IntentFilterVerificationResponse response =
1784                            (IntentFilterVerificationResponse) msg.obj;
1785
1786                    state.setVerifierResponse(response.callerUid, response.code);
1787
1788                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1789                            "IntentFilter verification with token:" + verificationId
1790                            + " and userId:" + userId
1791                            + " is settings verifier response with response code:"
1792                            + response.code);
1793
1794                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1795                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1796                                + response.getFailedDomainsString());
1797                    }
1798
1799                    if (state.isVerificationComplete()) {
1800                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1801                    } else {
1802                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1803                                "IntentFilter verification with token:" + verificationId
1804                                + " was not said to be complete");
1805                    }
1806
1807                    break;
1808                }
1809            }
1810        }
1811    }
1812
1813    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1814            boolean killApp, String[] grantedPermissions,
1815            boolean launchedForRestore, String installerPackage,
1816            IPackageInstallObserver2 installObserver) {
1817        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1818            // Send the removed broadcasts
1819            if (res.removedInfo != null) {
1820                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1821            }
1822
1823            // Now that we successfully installed the package, grant runtime
1824            // permissions if requested before broadcasting the install.
1825            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1826                    >= Build.VERSION_CODES.M) {
1827                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1828            }
1829
1830            final boolean update = res.removedInfo != null
1831                    && res.removedInfo.removedPackage != null;
1832
1833            // If this is the first time we have child packages for a disabled privileged
1834            // app that had no children, we grant requested runtime permissions to the new
1835            // children if the parent on the system image had them already granted.
1836            if (res.pkg.parentPackage != null) {
1837                synchronized (mPackages) {
1838                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1839                }
1840            }
1841
1842            synchronized (mPackages) {
1843                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1844            }
1845
1846            final String packageName = res.pkg.applicationInfo.packageName;
1847            Bundle extras = new Bundle(1);
1848            extras.putInt(Intent.EXTRA_UID, res.uid);
1849
1850            // Determine the set of users who are adding this package for
1851            // the first time vs. those who are seeing an update.
1852            int[] firstUsers = EMPTY_INT_ARRAY;
1853            int[] updateUsers = EMPTY_INT_ARRAY;
1854            if (res.origUsers == null || res.origUsers.length == 0) {
1855                firstUsers = res.newUsers;
1856            } else {
1857                for (int newUser : res.newUsers) {
1858                    boolean isNew = true;
1859                    for (int origUser : res.origUsers) {
1860                        if (origUser == newUser) {
1861                            isNew = false;
1862                            break;
1863                        }
1864                    }
1865                    if (isNew) {
1866                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1867                    } else {
1868                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1869                    }
1870                }
1871            }
1872
1873            // Send installed broadcasts if the install/update is not ephemeral
1874            if (!isEphemeral(res.pkg)) {
1875                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1876
1877                // Send added for users that see the package for the first time
1878                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1879                        extras, 0 /*flags*/, null /*targetPackage*/,
1880                        null /*finishedReceiver*/, firstUsers);
1881
1882                // Send added for users that don't see the package for the first time
1883                if (update) {
1884                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1885                }
1886                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1887                        extras, 0 /*flags*/, null /*targetPackage*/,
1888                        null /*finishedReceiver*/, updateUsers);
1889
1890                // Send replaced for users that don't see the package for the first time
1891                if (update) {
1892                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1893                            packageName, extras, 0 /*flags*/,
1894                            null /*targetPackage*/, null /*finishedReceiver*/,
1895                            updateUsers);
1896                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1897                            null /*package*/, null /*extras*/, 0 /*flags*/,
1898                            packageName /*targetPackage*/,
1899                            null /*finishedReceiver*/, updateUsers);
1900                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1901                    // First-install and we did a restore, so we're responsible for the
1902                    // first-launch broadcast.
1903                    if (DEBUG_BACKUP) {
1904                        Slog.i(TAG, "Post-restore of " + packageName
1905                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1906                    }
1907                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1908                }
1909
1910                // Send broadcast package appeared if forward locked/external for all users
1911                // treat asec-hosted packages like removable media on upgrade
1912                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1913                    if (DEBUG_INSTALL) {
1914                        Slog.i(TAG, "upgrading pkg " + res.pkg
1915                                + " is ASEC-hosted -> AVAILABLE");
1916                    }
1917                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1918                    ArrayList<String> pkgList = new ArrayList<>(1);
1919                    pkgList.add(packageName);
1920                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1921                }
1922            }
1923
1924            // Work that needs to happen on first install within each user
1925            if (firstUsers != null && firstUsers.length > 0) {
1926                synchronized (mPackages) {
1927                    for (int userId : firstUsers) {
1928                        // If this app is a browser and it's newly-installed for some
1929                        // users, clear any default-browser state in those users. The
1930                        // app's nature doesn't depend on the user, so we can just check
1931                        // its browser nature in any user and generalize.
1932                        if (packageIsBrowser(packageName, userId)) {
1933                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1934                        }
1935
1936                        // We may also need to apply pending (restored) runtime
1937                        // permission grants within these users.
1938                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1939                    }
1940                }
1941            }
1942
1943            // Log current value of "unknown sources" setting
1944            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1945                    getUnknownSourcesSettings());
1946
1947            // Force a gc to clear up things
1948            Runtime.getRuntime().gc();
1949
1950            // Remove the replaced package's older resources safely now
1951            // We delete after a gc for applications  on sdcard.
1952            if (res.removedInfo != null && res.removedInfo.args != null) {
1953                synchronized (mInstallLock) {
1954                    res.removedInfo.args.doPostDeleteLI(true);
1955                }
1956            }
1957        }
1958
1959        // If someone is watching installs - notify them
1960        if (installObserver != null) {
1961            try {
1962                Bundle extras = extrasForInstallResult(res);
1963                installObserver.onPackageInstalled(res.name, res.returnCode,
1964                        res.returnMsg, extras);
1965            } catch (RemoteException e) {
1966                Slog.i(TAG, "Observer no longer exists.");
1967            }
1968        }
1969    }
1970
1971    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1972            PackageParser.Package pkg) {
1973        if (pkg.parentPackage == null) {
1974            return;
1975        }
1976        if (pkg.requestedPermissions == null) {
1977            return;
1978        }
1979        final PackageSetting disabledSysParentPs = mSettings
1980                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1981        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1982                || !disabledSysParentPs.isPrivileged()
1983                || (disabledSysParentPs.childPackageNames != null
1984                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1985            return;
1986        }
1987        final int[] allUserIds = sUserManager.getUserIds();
1988        final int permCount = pkg.requestedPermissions.size();
1989        for (int i = 0; i < permCount; i++) {
1990            String permission = pkg.requestedPermissions.get(i);
1991            BasePermission bp = mSettings.mPermissions.get(permission);
1992            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1993                continue;
1994            }
1995            for (int userId : allUserIds) {
1996                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1997                        permission, userId)) {
1998                    grantRuntimePermission(pkg.packageName, permission, userId);
1999                }
2000            }
2001        }
2002    }
2003
2004    private StorageEventListener mStorageListener = new StorageEventListener() {
2005        @Override
2006        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2007            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2008                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2009                    final String volumeUuid = vol.getFsUuid();
2010
2011                    // Clean up any users or apps that were removed or recreated
2012                    // while this volume was missing
2013                    reconcileUsers(volumeUuid);
2014                    reconcileApps(volumeUuid);
2015
2016                    // Clean up any install sessions that expired or were
2017                    // cancelled while this volume was missing
2018                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2019
2020                    loadPrivatePackages(vol);
2021
2022                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2023                    unloadPrivatePackages(vol);
2024                }
2025            }
2026
2027            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2028                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2029                    updateExternalMediaStatus(true, false);
2030                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2031                    updateExternalMediaStatus(false, false);
2032                }
2033            }
2034        }
2035
2036        @Override
2037        public void onVolumeForgotten(String fsUuid) {
2038            if (TextUtils.isEmpty(fsUuid)) {
2039                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2040                return;
2041            }
2042
2043            // Remove any apps installed on the forgotten volume
2044            synchronized (mPackages) {
2045                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2046                for (PackageSetting ps : packages) {
2047                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2048                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
2049                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2050                }
2051
2052                mSettings.onVolumeForgotten(fsUuid);
2053                mSettings.writeLPr();
2054            }
2055        }
2056    };
2057
2058    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2059            String[] grantedPermissions) {
2060        for (int userId : userIds) {
2061            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2062        }
2063
2064        // We could have touched GID membership, so flush out packages.list
2065        synchronized (mPackages) {
2066            mSettings.writePackageListLPr();
2067        }
2068    }
2069
2070    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2071            String[] grantedPermissions) {
2072        SettingBase sb = (SettingBase) pkg.mExtras;
2073        if (sb == null) {
2074            return;
2075        }
2076
2077        PermissionsState permissionsState = sb.getPermissionsState();
2078
2079        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2080                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2081
2082        for (String permission : pkg.requestedPermissions) {
2083            final BasePermission bp;
2084            synchronized (mPackages) {
2085                bp = mSettings.mPermissions.get(permission);
2086            }
2087            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2088                    && (grantedPermissions == null
2089                           || ArrayUtils.contains(grantedPermissions, permission))) {
2090                final int flags = permissionsState.getPermissionFlags(permission, userId);
2091                // Installer cannot change immutable permissions.
2092                if ((flags & immutableFlags) == 0) {
2093                    grantRuntimePermission(pkg.packageName, permission, userId);
2094                }
2095            }
2096        }
2097    }
2098
2099    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2100        Bundle extras = null;
2101        switch (res.returnCode) {
2102            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2103                extras = new Bundle();
2104                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2105                        res.origPermission);
2106                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2107                        res.origPackage);
2108                break;
2109            }
2110            case PackageManager.INSTALL_SUCCEEDED: {
2111                extras = new Bundle();
2112                extras.putBoolean(Intent.EXTRA_REPLACING,
2113                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2114                break;
2115            }
2116        }
2117        return extras;
2118    }
2119
2120    void scheduleWriteSettingsLocked() {
2121        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2122            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2123        }
2124    }
2125
2126    void scheduleWritePackageListLocked(int userId) {
2127        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2128            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2129            msg.arg1 = userId;
2130            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2131        }
2132    }
2133
2134    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2135        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2136        scheduleWritePackageRestrictionsLocked(userId);
2137    }
2138
2139    void scheduleWritePackageRestrictionsLocked(int userId) {
2140        final int[] userIds = (userId == UserHandle.USER_ALL)
2141                ? sUserManager.getUserIds() : new int[]{userId};
2142        for (int nextUserId : userIds) {
2143            if (!sUserManager.exists(nextUserId)) return;
2144            mDirtyUsers.add(nextUserId);
2145            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2146                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2147            }
2148        }
2149    }
2150
2151    public static PackageManagerService main(Context context, Installer installer,
2152            boolean factoryTest, boolean onlyCore) {
2153        // Self-check for initial settings.
2154        PackageManagerServiceCompilerMapping.checkProperties();
2155
2156        PackageManagerService m = new PackageManagerService(context, installer,
2157                factoryTest, onlyCore);
2158        m.enableSystemUserPackages();
2159        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2160        // disabled after already being started.
2161        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2162                UserHandle.USER_SYSTEM);
2163        ServiceManager.addService("package", m);
2164        return m;
2165    }
2166
2167    private void enableSystemUserPackages() {
2168        if (!UserManager.isSplitSystemUser()) {
2169            return;
2170        }
2171        // For system user, enable apps based on the following conditions:
2172        // - app is whitelisted or belong to one of these groups:
2173        //   -- system app which has no launcher icons
2174        //   -- system app which has INTERACT_ACROSS_USERS permission
2175        //   -- system IME app
2176        // - app is not in the blacklist
2177        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2178        Set<String> enableApps = new ArraySet<>();
2179        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2180                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2181                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2182        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2183        enableApps.addAll(wlApps);
2184        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2185                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2186        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2187        enableApps.removeAll(blApps);
2188        Log.i(TAG, "Applications installed for system user: " + enableApps);
2189        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2190                UserHandle.SYSTEM);
2191        final int allAppsSize = allAps.size();
2192        synchronized (mPackages) {
2193            for (int i = 0; i < allAppsSize; i++) {
2194                String pName = allAps.get(i);
2195                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2196                // Should not happen, but we shouldn't be failing if it does
2197                if (pkgSetting == null) {
2198                    continue;
2199                }
2200                boolean install = enableApps.contains(pName);
2201                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2202                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2203                            + " for system user");
2204                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2205                }
2206            }
2207        }
2208    }
2209
2210    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2211        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2212                Context.DISPLAY_SERVICE);
2213        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2214    }
2215
2216    public PackageManagerService(Context context, Installer installer,
2217            boolean factoryTest, boolean onlyCore) {
2218        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2219                SystemClock.uptimeMillis());
2220
2221        if (mSdkVersion <= 0) {
2222            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2223        }
2224
2225        mContext = context;
2226        mFactoryTest = factoryTest;
2227        mOnlyCore = onlyCore;
2228        mMetrics = new DisplayMetrics();
2229        mSettings = new Settings(mPackages);
2230        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2231                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2232        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2233                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2234        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2235                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2236        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2237                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2238        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2239                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2240        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2241                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2242
2243        String separateProcesses = SystemProperties.get("debug.separate_processes");
2244        if (separateProcesses != null && separateProcesses.length() > 0) {
2245            if ("*".equals(separateProcesses)) {
2246                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2247                mSeparateProcesses = null;
2248                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2249            } else {
2250                mDefParseFlags = 0;
2251                mSeparateProcesses = separateProcesses.split(",");
2252                Slog.w(TAG, "Running with debug.separate_processes: "
2253                        + separateProcesses);
2254            }
2255        } else {
2256            mDefParseFlags = 0;
2257            mSeparateProcesses = null;
2258        }
2259
2260        mInstaller = installer;
2261        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2262                "*dexopt*");
2263        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2264
2265        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2266                FgThread.get().getLooper());
2267
2268        getDefaultDisplayMetrics(context, mMetrics);
2269
2270        SystemConfig systemConfig = SystemConfig.getInstance();
2271        mGlobalGids = systemConfig.getGlobalGids();
2272        mSystemPermissions = systemConfig.getSystemPermissions();
2273        mAvailableFeatures = systemConfig.getAvailableFeatures();
2274
2275        synchronized (mInstallLock) {
2276        // writer
2277        synchronized (mPackages) {
2278            mHandlerThread = new ServiceThread(TAG,
2279                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2280            mHandlerThread.start();
2281            mHandler = new PackageHandler(mHandlerThread.getLooper());
2282            mProcessLoggingHandler = new ProcessLoggingHandler();
2283            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2284
2285            File dataDir = Environment.getDataDirectory();
2286            mAppInstallDir = new File(dataDir, "app");
2287            mAppLib32InstallDir = new File(dataDir, "app-lib");
2288            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2289            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2290            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2291
2292            sUserManager = new UserManagerService(context, this, mPackages);
2293
2294            // Propagate permission configuration in to package manager.
2295            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2296                    = systemConfig.getPermissions();
2297            for (int i=0; i<permConfig.size(); i++) {
2298                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2299                BasePermission bp = mSettings.mPermissions.get(perm.name);
2300                if (bp == null) {
2301                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2302                    mSettings.mPermissions.put(perm.name, bp);
2303                }
2304                if (perm.gids != null) {
2305                    bp.setGids(perm.gids, perm.perUser);
2306                }
2307            }
2308
2309            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2310            for (int i=0; i<libConfig.size(); i++) {
2311                mSharedLibraries.put(libConfig.keyAt(i),
2312                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2313            }
2314
2315            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2316
2317            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2318
2319            String customResolverActivity = Resources.getSystem().getString(
2320                    R.string.config_customResolverActivity);
2321            if (TextUtils.isEmpty(customResolverActivity)) {
2322                customResolverActivity = null;
2323            } else {
2324                mCustomResolverComponentName = ComponentName.unflattenFromString(
2325                        customResolverActivity);
2326            }
2327
2328            long startTime = SystemClock.uptimeMillis();
2329
2330            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2331                    startTime);
2332
2333            // Set flag to monitor and not change apk file paths when
2334            // scanning install directories.
2335            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2336
2337            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2338            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2339
2340            if (bootClassPath == null) {
2341                Slog.w(TAG, "No BOOTCLASSPATH found!");
2342            }
2343
2344            if (systemServerClassPath == null) {
2345                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2346            }
2347
2348            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2349            final String[] dexCodeInstructionSets =
2350                    getDexCodeInstructionSets(
2351                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2352
2353            /**
2354             * Ensure all external libraries have had dexopt run on them.
2355             */
2356            if (mSharedLibraries.size() > 0) {
2357                // NOTE: For now, we're compiling these system "shared libraries"
2358                // (and framework jars) into all available architectures. It's possible
2359                // to compile them only when we come across an app that uses them (there's
2360                // already logic for that in scanPackageLI) but that adds some complexity.
2361                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2362                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2363                        final String lib = libEntry.path;
2364                        if (lib == null) {
2365                            continue;
2366                        }
2367
2368                        try {
2369                            // Shared libraries do not have profiles so we perform a full
2370                            // AOT compilation (if needed).
2371                            int dexoptNeeded = DexFile.getDexOptNeeded(
2372                                    lib, dexCodeInstructionSet,
2373                                    getCompilerFilterForReason(REASON_SHARED_APK),
2374                                    false /* newProfile */);
2375                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2376                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2377                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2378                                        getCompilerFilterForReason(REASON_SHARED_APK),
2379                                        StorageManager.UUID_PRIVATE_INTERNAL,
2380                                        SKIP_SHARED_LIBRARY_CHECK);
2381                            }
2382                        } catch (FileNotFoundException e) {
2383                            Slog.w(TAG, "Library not found: " + lib);
2384                        } catch (IOException | InstallerException e) {
2385                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2386                                    + e.getMessage());
2387                        }
2388                    }
2389                }
2390            }
2391
2392            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2393
2394            final VersionInfo ver = mSettings.getInternalVersion();
2395            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2396
2397            // when upgrading from pre-M, promote system app permissions from install to runtime
2398            mPromoteSystemApps =
2399                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2400
2401            // When upgrading from pre-N, we need to handle package extraction like first boot,
2402            // as there is no profiling data available.
2403            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2404
2405            // save off the names of pre-existing system packages prior to scanning; we don't
2406            // want to automatically grant runtime permissions for new system apps
2407            if (mPromoteSystemApps) {
2408                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2409                while (pkgSettingIter.hasNext()) {
2410                    PackageSetting ps = pkgSettingIter.next();
2411                    if (isSystemApp(ps)) {
2412                        mExistingSystemPackages.add(ps.name);
2413                    }
2414                }
2415            }
2416
2417            // Collect vendor overlay packages.
2418            // (Do this before scanning any apps.)
2419            // For security and version matching reason, only consider
2420            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2421            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2422            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2423                    | PackageParser.PARSE_IS_SYSTEM
2424                    | PackageParser.PARSE_IS_SYSTEM_DIR
2425                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2426
2427            // Find base frameworks (resource packages without code).
2428            scanDirTracedLI(frameworkDir, mDefParseFlags
2429                    | PackageParser.PARSE_IS_SYSTEM
2430                    | PackageParser.PARSE_IS_SYSTEM_DIR
2431                    | PackageParser.PARSE_IS_PRIVILEGED,
2432                    scanFlags | SCAN_NO_DEX, 0);
2433
2434            // Collected privileged system packages.
2435            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2436            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2437                    | PackageParser.PARSE_IS_SYSTEM
2438                    | PackageParser.PARSE_IS_SYSTEM_DIR
2439                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2440
2441            // Collect ordinary system packages.
2442            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2443            scanDirTracedLI(systemAppDir, mDefParseFlags
2444                    | PackageParser.PARSE_IS_SYSTEM
2445                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2446
2447            // Collect all vendor packages.
2448            File vendorAppDir = new File("/vendor/app");
2449            try {
2450                vendorAppDir = vendorAppDir.getCanonicalFile();
2451            } catch (IOException e) {
2452                // failed to look up canonical path, continue with original one
2453            }
2454            scanDirTracedLI(vendorAppDir, mDefParseFlags
2455                    | PackageParser.PARSE_IS_SYSTEM
2456                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2457
2458            // Collect all OEM packages.
2459            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2460            scanDirTracedLI(oemAppDir, mDefParseFlags
2461                    | PackageParser.PARSE_IS_SYSTEM
2462                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2463
2464            // Prune any system packages that no longer exist.
2465            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2466            if (!mOnlyCore) {
2467                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2468                while (psit.hasNext()) {
2469                    PackageSetting ps = psit.next();
2470
2471                    /*
2472                     * If this is not a system app, it can't be a
2473                     * disable system app.
2474                     */
2475                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2476                        continue;
2477                    }
2478
2479                    /*
2480                     * If the package is scanned, it's not erased.
2481                     */
2482                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2483                    if (scannedPkg != null) {
2484                        /*
2485                         * If the system app is both scanned and in the
2486                         * disabled packages list, then it must have been
2487                         * added via OTA. Remove it from the currently
2488                         * scanned package so the previously user-installed
2489                         * application can be scanned.
2490                         */
2491                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2492                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2493                                    + ps.name + "; removing system app.  Last known codePath="
2494                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2495                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2496                                    + scannedPkg.mVersionCode);
2497                            removePackageLI(scannedPkg, true);
2498                            mExpectingBetter.put(ps.name, ps.codePath);
2499                        }
2500
2501                        continue;
2502                    }
2503
2504                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2505                        psit.remove();
2506                        logCriticalInfo(Log.WARN, "System package " + ps.name
2507                                + " no longer exists; it's data will be wiped");
2508                        // Actual deletion of code and data will be handled by later
2509                        // reconciliation step
2510                    } else {
2511                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2512                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2513                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2514                        }
2515                    }
2516                }
2517            }
2518
2519            //look for any incomplete package installations
2520            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2521            for (int i = 0; i < deletePkgsList.size(); i++) {
2522                // Actual deletion of code and data will be handled by later
2523                // reconciliation step
2524                final String packageName = deletePkgsList.get(i).name;
2525                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2526                synchronized (mPackages) {
2527                    mSettings.removePackageLPw(packageName);
2528                }
2529            }
2530
2531            //delete tmp files
2532            deleteTempPackageFiles();
2533
2534            // Remove any shared userIDs that have no associated packages
2535            mSettings.pruneSharedUsersLPw();
2536
2537            if (!mOnlyCore) {
2538                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2539                        SystemClock.uptimeMillis());
2540                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2541
2542                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2543                        | PackageParser.PARSE_FORWARD_LOCK,
2544                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2545
2546                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2547                        | PackageParser.PARSE_IS_EPHEMERAL,
2548                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2549
2550                /**
2551                 * Remove disable package settings for any updated system
2552                 * apps that were removed via an OTA. If they're not a
2553                 * previously-updated app, remove them completely.
2554                 * Otherwise, just revoke their system-level permissions.
2555                 */
2556                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2557                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2558                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2559
2560                    String msg;
2561                    if (deletedPkg == null) {
2562                        msg = "Updated system package " + deletedAppName
2563                                + " no longer exists; it's data will be wiped";
2564                        // Actual deletion of code and data will be handled by later
2565                        // reconciliation step
2566                    } else {
2567                        msg = "Updated system app + " + deletedAppName
2568                                + " no longer present; removing system privileges for "
2569                                + deletedAppName;
2570
2571                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2572
2573                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2574                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2575                    }
2576                    logCriticalInfo(Log.WARN, msg);
2577                }
2578
2579                /**
2580                 * Make sure all system apps that we expected to appear on
2581                 * the userdata partition actually showed up. If they never
2582                 * appeared, crawl back and revive the system version.
2583                 */
2584                for (int i = 0; i < mExpectingBetter.size(); i++) {
2585                    final String packageName = mExpectingBetter.keyAt(i);
2586                    if (!mPackages.containsKey(packageName)) {
2587                        final File scanFile = mExpectingBetter.valueAt(i);
2588
2589                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2590                                + " but never showed up; reverting to system");
2591
2592                        int reparseFlags = mDefParseFlags;
2593                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2594                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2595                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2596                                    | PackageParser.PARSE_IS_PRIVILEGED;
2597                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2598                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2599                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2600                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2601                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2602                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2603                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2604                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2605                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2606                        } else {
2607                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2608                            continue;
2609                        }
2610
2611                        mSettings.enableSystemPackageLPw(packageName);
2612
2613                        try {
2614                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2615                        } catch (PackageManagerException e) {
2616                            Slog.e(TAG, "Failed to parse original system package: "
2617                                    + e.getMessage());
2618                        }
2619                    }
2620                }
2621            }
2622            mExpectingBetter.clear();
2623
2624            // Resolve protected action filters. Only the setup wizard is allowed to
2625            // have a high priority filter for these actions.
2626            mSetupWizardPackage = getSetupWizardPackageName();
2627            if (mProtectedFilters.size() > 0) {
2628                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2629                    Slog.i(TAG, "No setup wizard;"
2630                        + " All protected intents capped to priority 0");
2631                }
2632                for (ActivityIntentInfo filter : mProtectedFilters) {
2633                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2634                        if (DEBUG_FILTERS) {
2635                            Slog.i(TAG, "Found setup wizard;"
2636                                + " allow priority " + filter.getPriority() + ";"
2637                                + " package: " + filter.activity.info.packageName
2638                                + " activity: " + filter.activity.className
2639                                + " priority: " + filter.getPriority());
2640                        }
2641                        // skip setup wizard; allow it to keep the high priority filter
2642                        continue;
2643                    }
2644                    Slog.w(TAG, "Protected action; cap priority to 0;"
2645                            + " package: " + filter.activity.info.packageName
2646                            + " activity: " + filter.activity.className
2647                            + " origPrio: " + filter.getPriority());
2648                    filter.setPriority(0);
2649                }
2650            }
2651            mDeferProtectedFilters = false;
2652            mProtectedFilters.clear();
2653
2654            // Now that we know all of the shared libraries, update all clients to have
2655            // the correct library paths.
2656            updateAllSharedLibrariesLPw();
2657
2658            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2659                // NOTE: We ignore potential failures here during a system scan (like
2660                // the rest of the commands above) because there's precious little we
2661                // can do about it. A settings error is reported, though.
2662                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2663                        false /* boot complete */);
2664            }
2665
2666            // Now that we know all the packages we are keeping,
2667            // read and update their last usage times.
2668            mPackageUsage.readLP();
2669
2670            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2671                    SystemClock.uptimeMillis());
2672            Slog.i(TAG, "Time to scan packages: "
2673                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2674                    + " seconds");
2675
2676            // If the platform SDK has changed since the last time we booted,
2677            // we need to re-grant app permission to catch any new ones that
2678            // appear.  This is really a hack, and means that apps can in some
2679            // cases get permissions that the user didn't initially explicitly
2680            // allow...  it would be nice to have some better way to handle
2681            // this situation.
2682            int updateFlags = UPDATE_PERMISSIONS_ALL;
2683            if (ver.sdkVersion != mSdkVersion) {
2684                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2685                        + mSdkVersion + "; regranting permissions for internal storage");
2686                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2687            }
2688            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2689            ver.sdkVersion = mSdkVersion;
2690
2691            // If this is the first boot or an update from pre-M, and it is a normal
2692            // boot, then we need to initialize the default preferred apps across
2693            // all defined users.
2694            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2695                for (UserInfo user : sUserManager.getUsers(true)) {
2696                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2697                    applyFactoryDefaultBrowserLPw(user.id);
2698                    primeDomainVerificationsLPw(user.id);
2699                }
2700            }
2701
2702            // Prepare storage for system user really early during boot,
2703            // since core system apps like SettingsProvider and SystemUI
2704            // can't wait for user to start
2705            final int storageFlags;
2706            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2707                storageFlags = StorageManager.FLAG_STORAGE_DE;
2708            } else {
2709                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2710            }
2711            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2712                    storageFlags);
2713
2714            // If this is first boot after an OTA, and a normal boot, then
2715            // we need to clear code cache directories.
2716            // Note that we do *not* clear the application profiles. These remain valid
2717            // across OTAs and are used to drive profile verification (post OTA) and
2718            // profile compilation (without waiting to collect a fresh set of profiles).
2719            if (mIsUpgrade && !onlyCore) {
2720                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2721                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2722                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2723                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2724                        // No apps are running this early, so no need to freeze
2725                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2726                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2727                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2728                    }
2729                }
2730                ver.fingerprint = Build.FINGERPRINT;
2731            }
2732
2733            checkDefaultBrowser();
2734
2735            // clear only after permissions and other defaults have been updated
2736            mExistingSystemPackages.clear();
2737            mPromoteSystemApps = false;
2738
2739            // All the changes are done during package scanning.
2740            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2741
2742            // can downgrade to reader
2743            mSettings.writeLPr();
2744
2745            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2746            // early on (before the package manager declares itself as early) because other
2747            // components in the system server might ask for package contexts for these apps.
2748            //
2749            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2750            // (i.e, that the data partition is unavailable).
2751            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2752                long start = System.nanoTime();
2753                List<PackageParser.Package> coreApps = new ArrayList<>();
2754                for (PackageParser.Package pkg : mPackages.values()) {
2755                    if (pkg.coreApp) {
2756                        coreApps.add(pkg);
2757                    }
2758                }
2759
2760                int[] stats = performDexOpt(coreApps, false,
2761                        getCompilerFilterForReason(REASON_CORE_APP));
2762
2763                final int elapsedTimeSeconds =
2764                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2765                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2766
2767                if (DEBUG_DEXOPT) {
2768                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2769                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2770                }
2771
2772
2773                // TODO: Should we log these stats to tron too ?
2774                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2775                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2776                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2777                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2778            }
2779
2780            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2781                    SystemClock.uptimeMillis());
2782
2783            if (!mOnlyCore) {
2784                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2785                mRequiredInstallerPackage = getRequiredInstallerLPr();
2786                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2787                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2788                        mIntentFilterVerifierComponent);
2789                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2790                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2791                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2792                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2793            } else {
2794                mRequiredVerifierPackage = null;
2795                mRequiredInstallerPackage = null;
2796                mIntentFilterVerifierComponent = null;
2797                mIntentFilterVerifier = null;
2798                mServicesSystemSharedLibraryPackageName = null;
2799                mSharedSystemSharedLibraryPackageName = null;
2800            }
2801
2802            mInstallerService = new PackageInstallerService(context, this);
2803
2804            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2805            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2806            // both the installer and resolver must be present to enable ephemeral
2807            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2808                if (DEBUG_EPHEMERAL) {
2809                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2810                            + " installer:" + ephemeralInstallerComponent);
2811                }
2812                mEphemeralResolverComponent = ephemeralResolverComponent;
2813                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2814                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2815                mEphemeralResolverConnection =
2816                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2817            } else {
2818                if (DEBUG_EPHEMERAL) {
2819                    final String missingComponent =
2820                            (ephemeralResolverComponent == null)
2821                            ? (ephemeralInstallerComponent == null)
2822                                    ? "resolver and installer"
2823                                    : "resolver"
2824                            : "installer";
2825                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2826                }
2827                mEphemeralResolverComponent = null;
2828                mEphemeralInstallerComponent = null;
2829                mEphemeralResolverConnection = null;
2830            }
2831
2832            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2833        } // synchronized (mPackages)
2834        } // synchronized (mInstallLock)
2835
2836        // Now after opening every single application zip, make sure they
2837        // are all flushed.  Not really needed, but keeps things nice and
2838        // tidy.
2839        Runtime.getRuntime().gc();
2840
2841        // The initial scanning above does many calls into installd while
2842        // holding the mPackages lock, but we're mostly interested in yelling
2843        // once we have a booted system.
2844        mInstaller.setWarnIfHeld(mPackages);
2845
2846        // Expose private service for system components to use.
2847        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2848    }
2849
2850    @Override
2851    public boolean isFirstBoot() {
2852        return !mRestoredSettings;
2853    }
2854
2855    @Override
2856    public boolean isOnlyCoreApps() {
2857        return mOnlyCore;
2858    }
2859
2860    @Override
2861    public boolean isUpgrade() {
2862        return mIsUpgrade;
2863    }
2864
2865    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2866        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2867
2868        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2869                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2870                UserHandle.USER_SYSTEM);
2871        if (matches.size() == 1) {
2872            return matches.get(0).getComponentInfo().packageName;
2873        } else {
2874            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2875            return null;
2876        }
2877    }
2878
2879    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2880        synchronized (mPackages) {
2881            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2882            if (libraryEntry == null) {
2883                throw new IllegalStateException("Missing required shared library:" + libraryName);
2884            }
2885            return libraryEntry.apk;
2886        }
2887    }
2888
2889    private @NonNull String getRequiredInstallerLPr() {
2890        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2891        intent.addCategory(Intent.CATEGORY_DEFAULT);
2892        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2893
2894        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2895                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2896                UserHandle.USER_SYSTEM);
2897        if (matches.size() == 1) {
2898            ResolveInfo resolveInfo = matches.get(0);
2899            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2900                throw new RuntimeException("The installer must be a privileged app");
2901            }
2902            return matches.get(0).getComponentInfo().packageName;
2903        } else {
2904            throw new RuntimeException("There must be exactly one installer; found " + matches);
2905        }
2906    }
2907
2908    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2909        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2910
2911        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2912                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2913                UserHandle.USER_SYSTEM);
2914        ResolveInfo best = null;
2915        final int N = matches.size();
2916        for (int i = 0; i < N; i++) {
2917            final ResolveInfo cur = matches.get(i);
2918            final String packageName = cur.getComponentInfo().packageName;
2919            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2920                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2921                continue;
2922            }
2923
2924            if (best == null || cur.priority > best.priority) {
2925                best = cur;
2926            }
2927        }
2928
2929        if (best != null) {
2930            return best.getComponentInfo().getComponentName();
2931        } else {
2932            throw new RuntimeException("There must be at least one intent filter verifier");
2933        }
2934    }
2935
2936    private @Nullable ComponentName getEphemeralResolverLPr() {
2937        final String[] packageArray =
2938                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2939        if (packageArray.length == 0) {
2940            if (DEBUG_EPHEMERAL) {
2941                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2942            }
2943            return null;
2944        }
2945
2946        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2947        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2948                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2949                UserHandle.USER_SYSTEM);
2950
2951        final int N = resolvers.size();
2952        if (N == 0) {
2953            if (DEBUG_EPHEMERAL) {
2954                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2955            }
2956            return null;
2957        }
2958
2959        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2960        for (int i = 0; i < N; i++) {
2961            final ResolveInfo info = resolvers.get(i);
2962
2963            if (info.serviceInfo == null) {
2964                continue;
2965            }
2966
2967            final String packageName = info.serviceInfo.packageName;
2968            if (!possiblePackages.contains(packageName)) {
2969                if (DEBUG_EPHEMERAL) {
2970                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2971                            + " pkg: " + packageName + ", info:" + info);
2972                }
2973                continue;
2974            }
2975
2976            if (DEBUG_EPHEMERAL) {
2977                Slog.v(TAG, "Ephemeral resolver found;"
2978                        + " pkg: " + packageName + ", info:" + info);
2979            }
2980            return new ComponentName(packageName, info.serviceInfo.name);
2981        }
2982        if (DEBUG_EPHEMERAL) {
2983            Slog.v(TAG, "Ephemeral resolver NOT found");
2984        }
2985        return null;
2986    }
2987
2988    private @Nullable ComponentName getEphemeralInstallerLPr() {
2989        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2990        intent.addCategory(Intent.CATEGORY_DEFAULT);
2991        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2992
2993        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2994                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2995                UserHandle.USER_SYSTEM);
2996        if (matches.size() == 0) {
2997            return null;
2998        } else if (matches.size() == 1) {
2999            return matches.get(0).getComponentInfo().getComponentName();
3000        } else {
3001            throw new RuntimeException(
3002                    "There must be at most one ephemeral installer; found " + matches);
3003        }
3004    }
3005
3006    private void primeDomainVerificationsLPw(int userId) {
3007        if (DEBUG_DOMAIN_VERIFICATION) {
3008            Slog.d(TAG, "Priming domain verifications in user " + userId);
3009        }
3010
3011        SystemConfig systemConfig = SystemConfig.getInstance();
3012        ArraySet<String> packages = systemConfig.getLinkedApps();
3013        ArraySet<String> domains = new ArraySet<String>();
3014
3015        for (String packageName : packages) {
3016            PackageParser.Package pkg = mPackages.get(packageName);
3017            if (pkg != null) {
3018                if (!pkg.isSystemApp()) {
3019                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3020                    continue;
3021                }
3022
3023                domains.clear();
3024                for (PackageParser.Activity a : pkg.activities) {
3025                    for (ActivityIntentInfo filter : a.intents) {
3026                        if (hasValidDomains(filter)) {
3027                            domains.addAll(filter.getHostsList());
3028                        }
3029                    }
3030                }
3031
3032                if (domains.size() > 0) {
3033                    if (DEBUG_DOMAIN_VERIFICATION) {
3034                        Slog.v(TAG, "      + " + packageName);
3035                    }
3036                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3037                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3038                    // and then 'always' in the per-user state actually used for intent resolution.
3039                    final IntentFilterVerificationInfo ivi;
3040                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
3041                            new ArrayList<String>(domains));
3042                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3043                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3044                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3045                } else {
3046                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3047                            + "' does not handle web links");
3048                }
3049            } else {
3050                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3051            }
3052        }
3053
3054        scheduleWritePackageRestrictionsLocked(userId);
3055        scheduleWriteSettingsLocked();
3056    }
3057
3058    private void applyFactoryDefaultBrowserLPw(int userId) {
3059        // The default browser app's package name is stored in a string resource,
3060        // with a product-specific overlay used for vendor customization.
3061        String browserPkg = mContext.getResources().getString(
3062                com.android.internal.R.string.default_browser);
3063        if (!TextUtils.isEmpty(browserPkg)) {
3064            // non-empty string => required to be a known package
3065            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3066            if (ps == null) {
3067                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3068                browserPkg = null;
3069            } else {
3070                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3071            }
3072        }
3073
3074        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3075        // default.  If there's more than one, just leave everything alone.
3076        if (browserPkg == null) {
3077            calculateDefaultBrowserLPw(userId);
3078        }
3079    }
3080
3081    private void calculateDefaultBrowserLPw(int userId) {
3082        List<String> allBrowsers = resolveAllBrowserApps(userId);
3083        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3084        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3085    }
3086
3087    private List<String> resolveAllBrowserApps(int userId) {
3088        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3089        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3090                PackageManager.MATCH_ALL, userId);
3091
3092        final int count = list.size();
3093        List<String> result = new ArrayList<String>(count);
3094        for (int i=0; i<count; i++) {
3095            ResolveInfo info = list.get(i);
3096            if (info.activityInfo == null
3097                    || !info.handleAllWebDataURI
3098                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3099                    || result.contains(info.activityInfo.packageName)) {
3100                continue;
3101            }
3102            result.add(info.activityInfo.packageName);
3103        }
3104
3105        return result;
3106    }
3107
3108    private boolean packageIsBrowser(String packageName, int userId) {
3109        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3110                PackageManager.MATCH_ALL, userId);
3111        final int N = list.size();
3112        for (int i = 0; i < N; i++) {
3113            ResolveInfo info = list.get(i);
3114            if (packageName.equals(info.activityInfo.packageName)) {
3115                return true;
3116            }
3117        }
3118        return false;
3119    }
3120
3121    private void checkDefaultBrowser() {
3122        final int myUserId = UserHandle.myUserId();
3123        final String packageName = getDefaultBrowserPackageName(myUserId);
3124        if (packageName != null) {
3125            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3126            if (info == null) {
3127                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3128                synchronized (mPackages) {
3129                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3130                }
3131            }
3132        }
3133    }
3134
3135    @Override
3136    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3137            throws RemoteException {
3138        try {
3139            return super.onTransact(code, data, reply, flags);
3140        } catch (RuntimeException e) {
3141            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3142                Slog.wtf(TAG, "Package Manager Crash", e);
3143            }
3144            throw e;
3145        }
3146    }
3147
3148    static int[] appendInts(int[] cur, int[] add) {
3149        if (add == null) return cur;
3150        if (cur == null) return add;
3151        final int N = add.length;
3152        for (int i=0; i<N; i++) {
3153            cur = appendInt(cur, add[i]);
3154        }
3155        return cur;
3156    }
3157
3158    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3159        if (!sUserManager.exists(userId)) return null;
3160        if (ps == null) {
3161            return null;
3162        }
3163        final PackageParser.Package p = ps.pkg;
3164        if (p == null) {
3165            return null;
3166        }
3167
3168        final PermissionsState permissionsState = ps.getPermissionsState();
3169
3170        final int[] gids = permissionsState.computeGids(userId);
3171        final Set<String> permissions = permissionsState.getPermissions(userId);
3172        final PackageUserState state = ps.readUserState(userId);
3173
3174        return PackageParser.generatePackageInfo(p, gids, flags,
3175                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3176    }
3177
3178    @Override
3179    public void checkPackageStartable(String packageName, int userId) {
3180        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3181
3182        synchronized (mPackages) {
3183            final PackageSetting ps = mSettings.mPackages.get(packageName);
3184            if (ps == null) {
3185                throw new SecurityException("Package " + packageName + " was not found!");
3186            }
3187
3188            if (!ps.getInstalled(userId)) {
3189                throw new SecurityException(
3190                        "Package " + packageName + " was not installed for user " + userId + "!");
3191            }
3192
3193            if (mSafeMode && !ps.isSystem()) {
3194                throw new SecurityException("Package " + packageName + " not a system app!");
3195            }
3196
3197            if (mFrozenPackages.contains(packageName)) {
3198                throw new SecurityException("Package " + packageName + " is currently frozen!");
3199            }
3200
3201            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3202                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3203                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3204            }
3205        }
3206    }
3207
3208    @Override
3209    public boolean isPackageAvailable(String packageName, int userId) {
3210        if (!sUserManager.exists(userId)) return false;
3211        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3212                false /* requireFullPermission */, false /* checkShell */, "is package available");
3213        synchronized (mPackages) {
3214            PackageParser.Package p = mPackages.get(packageName);
3215            if (p != null) {
3216                final PackageSetting ps = (PackageSetting) p.mExtras;
3217                if (ps != null) {
3218                    final PackageUserState state = ps.readUserState(userId);
3219                    if (state != null) {
3220                        return PackageParser.isAvailable(state);
3221                    }
3222                }
3223            }
3224        }
3225        return false;
3226    }
3227
3228    @Override
3229    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3230        if (!sUserManager.exists(userId)) return null;
3231        flags = updateFlagsForPackage(flags, userId, packageName);
3232        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3233                false /* requireFullPermission */, false /* checkShell */, "get package info");
3234        // reader
3235        synchronized (mPackages) {
3236            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3237            PackageParser.Package p = null;
3238            if (matchFactoryOnly) {
3239                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3240                if (ps != null) {
3241                    return generatePackageInfo(ps, flags, userId);
3242                }
3243            }
3244            if (p == null) {
3245                p = mPackages.get(packageName);
3246                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3247                    return null;
3248                }
3249            }
3250            if (DEBUG_PACKAGE_INFO)
3251                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3252            if (p != null) {
3253                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3254            }
3255            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3256                final PackageSetting ps = mSettings.mPackages.get(packageName);
3257                return generatePackageInfo(ps, flags, userId);
3258            }
3259        }
3260        return null;
3261    }
3262
3263    @Override
3264    public String[] currentToCanonicalPackageNames(String[] names) {
3265        String[] out = new String[names.length];
3266        // reader
3267        synchronized (mPackages) {
3268            for (int i=names.length-1; i>=0; i--) {
3269                PackageSetting ps = mSettings.mPackages.get(names[i]);
3270                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3271            }
3272        }
3273        return out;
3274    }
3275
3276    @Override
3277    public String[] canonicalToCurrentPackageNames(String[] names) {
3278        String[] out = new String[names.length];
3279        // reader
3280        synchronized (mPackages) {
3281            for (int i=names.length-1; i>=0; i--) {
3282                String cur = mSettings.mRenamedPackages.get(names[i]);
3283                out[i] = cur != null ? cur : names[i];
3284            }
3285        }
3286        return out;
3287    }
3288
3289    @Override
3290    public int getPackageUid(String packageName, int flags, int userId) {
3291        if (!sUserManager.exists(userId)) return -1;
3292        flags = updateFlagsForPackage(flags, userId, packageName);
3293        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3294                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3295
3296        // reader
3297        synchronized (mPackages) {
3298            final PackageParser.Package p = mPackages.get(packageName);
3299            if (p != null && p.isMatch(flags)) {
3300                return UserHandle.getUid(userId, p.applicationInfo.uid);
3301            }
3302            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3303                final PackageSetting ps = mSettings.mPackages.get(packageName);
3304                if (ps != null && ps.isMatch(flags)) {
3305                    return UserHandle.getUid(userId, ps.appId);
3306                }
3307            }
3308        }
3309
3310        return -1;
3311    }
3312
3313    @Override
3314    public int[] getPackageGids(String packageName, int flags, int userId) {
3315        if (!sUserManager.exists(userId)) return null;
3316        flags = updateFlagsForPackage(flags, userId, packageName);
3317        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3318                false /* requireFullPermission */, false /* checkShell */,
3319                "getPackageGids");
3320
3321        // reader
3322        synchronized (mPackages) {
3323            final PackageParser.Package p = mPackages.get(packageName);
3324            if (p != null && p.isMatch(flags)) {
3325                PackageSetting ps = (PackageSetting) p.mExtras;
3326                return ps.getPermissionsState().computeGids(userId);
3327            }
3328            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3329                final PackageSetting ps = mSettings.mPackages.get(packageName);
3330                if (ps != null && ps.isMatch(flags)) {
3331                    return ps.getPermissionsState().computeGids(userId);
3332                }
3333            }
3334        }
3335
3336        return null;
3337    }
3338
3339    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3340        if (bp.perm != null) {
3341            return PackageParser.generatePermissionInfo(bp.perm, flags);
3342        }
3343        PermissionInfo pi = new PermissionInfo();
3344        pi.name = bp.name;
3345        pi.packageName = bp.sourcePackage;
3346        pi.nonLocalizedLabel = bp.name;
3347        pi.protectionLevel = bp.protectionLevel;
3348        return pi;
3349    }
3350
3351    @Override
3352    public PermissionInfo getPermissionInfo(String name, int flags) {
3353        // reader
3354        synchronized (mPackages) {
3355            final BasePermission p = mSettings.mPermissions.get(name);
3356            if (p != null) {
3357                return generatePermissionInfo(p, flags);
3358            }
3359            return null;
3360        }
3361    }
3362
3363    @Override
3364    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3365            int flags) {
3366        // reader
3367        synchronized (mPackages) {
3368            if (group != null && !mPermissionGroups.containsKey(group)) {
3369                // This is thrown as NameNotFoundException
3370                return null;
3371            }
3372
3373            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3374            for (BasePermission p : mSettings.mPermissions.values()) {
3375                if (group == null) {
3376                    if (p.perm == null || p.perm.info.group == null) {
3377                        out.add(generatePermissionInfo(p, flags));
3378                    }
3379                } else {
3380                    if (p.perm != null && group.equals(p.perm.info.group)) {
3381                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3382                    }
3383                }
3384            }
3385            return new ParceledListSlice<>(out);
3386        }
3387    }
3388
3389    @Override
3390    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3391        // reader
3392        synchronized (mPackages) {
3393            return PackageParser.generatePermissionGroupInfo(
3394                    mPermissionGroups.get(name), flags);
3395        }
3396    }
3397
3398    @Override
3399    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3400        // reader
3401        synchronized (mPackages) {
3402            final int N = mPermissionGroups.size();
3403            ArrayList<PermissionGroupInfo> out
3404                    = new ArrayList<PermissionGroupInfo>(N);
3405            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3406                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3407            }
3408            return new ParceledListSlice<>(out);
3409        }
3410    }
3411
3412    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3413            int userId) {
3414        if (!sUserManager.exists(userId)) return null;
3415        PackageSetting ps = mSettings.mPackages.get(packageName);
3416        if (ps != null) {
3417            if (ps.pkg == null) {
3418                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3419                if (pInfo != null) {
3420                    return pInfo.applicationInfo;
3421                }
3422                return null;
3423            }
3424            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3425                    ps.readUserState(userId), userId);
3426        }
3427        return null;
3428    }
3429
3430    @Override
3431    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3432        if (!sUserManager.exists(userId)) return null;
3433        flags = updateFlagsForApplication(flags, userId, packageName);
3434        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3435                false /* requireFullPermission */, false /* checkShell */, "get application info");
3436        // writer
3437        synchronized (mPackages) {
3438            PackageParser.Package p = mPackages.get(packageName);
3439            if (DEBUG_PACKAGE_INFO) Log.v(
3440                    TAG, "getApplicationInfo " + packageName
3441                    + ": " + p);
3442            if (p != null) {
3443                PackageSetting ps = mSettings.mPackages.get(packageName);
3444                if (ps == null) return null;
3445                // Note: isEnabledLP() does not apply here - always return info
3446                return PackageParser.generateApplicationInfo(
3447                        p, flags, ps.readUserState(userId), userId);
3448            }
3449            if ("android".equals(packageName)||"system".equals(packageName)) {
3450                return mAndroidApplication;
3451            }
3452            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3453                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3454            }
3455        }
3456        return null;
3457    }
3458
3459    @Override
3460    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3461            final IPackageDataObserver observer) {
3462        mContext.enforceCallingOrSelfPermission(
3463                android.Manifest.permission.CLEAR_APP_CACHE, null);
3464        // Queue up an async operation since clearing cache may take a little while.
3465        mHandler.post(new Runnable() {
3466            public void run() {
3467                mHandler.removeCallbacks(this);
3468                boolean success = true;
3469                synchronized (mInstallLock) {
3470                    try {
3471                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3472                    } catch (InstallerException e) {
3473                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3474                        success = false;
3475                    }
3476                }
3477                if (observer != null) {
3478                    try {
3479                        observer.onRemoveCompleted(null, success);
3480                    } catch (RemoteException e) {
3481                        Slog.w(TAG, "RemoveException when invoking call back");
3482                    }
3483                }
3484            }
3485        });
3486    }
3487
3488    @Override
3489    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3490            final IntentSender pi) {
3491        mContext.enforceCallingOrSelfPermission(
3492                android.Manifest.permission.CLEAR_APP_CACHE, null);
3493        // Queue up an async operation since clearing cache may take a little while.
3494        mHandler.post(new Runnable() {
3495            public void run() {
3496                mHandler.removeCallbacks(this);
3497                boolean success = true;
3498                synchronized (mInstallLock) {
3499                    try {
3500                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3501                    } catch (InstallerException e) {
3502                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3503                        success = false;
3504                    }
3505                }
3506                if(pi != null) {
3507                    try {
3508                        // Callback via pending intent
3509                        int code = success ? 1 : 0;
3510                        pi.sendIntent(null, code, null,
3511                                null, null);
3512                    } catch (SendIntentException e1) {
3513                        Slog.i(TAG, "Failed to send pending intent");
3514                    }
3515                }
3516            }
3517        });
3518    }
3519
3520    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3521        synchronized (mInstallLock) {
3522            try {
3523                mInstaller.freeCache(volumeUuid, freeStorageSize);
3524            } catch (InstallerException e) {
3525                throw new IOException("Failed to free enough space", e);
3526            }
3527        }
3528    }
3529
3530    /**
3531     * Update given flags based on encryption status of current user.
3532     */
3533    private int updateFlags(int flags, int userId) {
3534        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3535                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3536            // Caller expressed an explicit opinion about what encryption
3537            // aware/unaware components they want to see, so fall through and
3538            // give them what they want
3539        } else {
3540            // Caller expressed no opinion, so match based on user state
3541            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3542                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3543            } else {
3544                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3545            }
3546        }
3547        return flags;
3548    }
3549
3550    private UserManagerInternal getUserManagerInternal() {
3551        if (mUserManagerInternal == null) {
3552            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3553        }
3554        return mUserManagerInternal;
3555    }
3556
3557    /**
3558     * Update given flags when being used to request {@link PackageInfo}.
3559     */
3560    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3561        boolean triaged = true;
3562        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3563                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3564            // Caller is asking for component details, so they'd better be
3565            // asking for specific encryption matching behavior, or be triaged
3566            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3567                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3568                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3569                triaged = false;
3570            }
3571        }
3572        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3573                | PackageManager.MATCH_SYSTEM_ONLY
3574                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3575            triaged = false;
3576        }
3577        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3578            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3579                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3580        }
3581        return updateFlags(flags, userId);
3582    }
3583
3584    /**
3585     * Update given flags when being used to request {@link ApplicationInfo}.
3586     */
3587    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3588        return updateFlagsForPackage(flags, userId, cookie);
3589    }
3590
3591    /**
3592     * Update given flags when being used to request {@link ComponentInfo}.
3593     */
3594    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3595        if (cookie instanceof Intent) {
3596            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3597                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3598            }
3599        }
3600
3601        boolean triaged = true;
3602        // Caller is asking for component details, so they'd better be
3603        // asking for specific encryption matching behavior, or be triaged
3604        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3605                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3606                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3607            triaged = false;
3608        }
3609        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3610            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3611                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3612        }
3613
3614        return updateFlags(flags, userId);
3615    }
3616
3617    /**
3618     * Update given flags when being used to request {@link ResolveInfo}.
3619     */
3620    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3621        // Safe mode means we shouldn't match any third-party components
3622        if (mSafeMode) {
3623            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3624        }
3625
3626        return updateFlagsForComponent(flags, userId, cookie);
3627    }
3628
3629    @Override
3630    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3631        if (!sUserManager.exists(userId)) return null;
3632        flags = updateFlagsForComponent(flags, userId, component);
3633        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3634                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3635        synchronized (mPackages) {
3636            PackageParser.Activity a = mActivities.mActivities.get(component);
3637
3638            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3639            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3640                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3641                if (ps == null) return null;
3642                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3643                        userId);
3644            }
3645            if (mResolveComponentName.equals(component)) {
3646                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3647                        new PackageUserState(), userId);
3648            }
3649        }
3650        return null;
3651    }
3652
3653    @Override
3654    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3655            String resolvedType) {
3656        synchronized (mPackages) {
3657            if (component.equals(mResolveComponentName)) {
3658                // The resolver supports EVERYTHING!
3659                return true;
3660            }
3661            PackageParser.Activity a = mActivities.mActivities.get(component);
3662            if (a == null) {
3663                return false;
3664            }
3665            for (int i=0; i<a.intents.size(); i++) {
3666                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3667                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3668                    return true;
3669                }
3670            }
3671            return false;
3672        }
3673    }
3674
3675    @Override
3676    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3677        if (!sUserManager.exists(userId)) return null;
3678        flags = updateFlagsForComponent(flags, userId, component);
3679        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3680                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3681        synchronized (mPackages) {
3682            PackageParser.Activity a = mReceivers.mActivities.get(component);
3683            if (DEBUG_PACKAGE_INFO) Log.v(
3684                TAG, "getReceiverInfo " + component + ": " + a);
3685            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3686                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3687                if (ps == null) return null;
3688                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3689                        userId);
3690            }
3691        }
3692        return null;
3693    }
3694
3695    @Override
3696    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3697        if (!sUserManager.exists(userId)) return null;
3698        flags = updateFlagsForComponent(flags, userId, component);
3699        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3700                false /* requireFullPermission */, false /* checkShell */, "get service info");
3701        synchronized (mPackages) {
3702            PackageParser.Service s = mServices.mServices.get(component);
3703            if (DEBUG_PACKAGE_INFO) Log.v(
3704                TAG, "getServiceInfo " + component + ": " + s);
3705            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3706                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3707                if (ps == null) return null;
3708                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3709                        userId);
3710            }
3711        }
3712        return null;
3713    }
3714
3715    @Override
3716    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3717        if (!sUserManager.exists(userId)) return null;
3718        flags = updateFlagsForComponent(flags, userId, component);
3719        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3720                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3721        synchronized (mPackages) {
3722            PackageParser.Provider p = mProviders.mProviders.get(component);
3723            if (DEBUG_PACKAGE_INFO) Log.v(
3724                TAG, "getProviderInfo " + component + ": " + p);
3725            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3726                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3727                if (ps == null) return null;
3728                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3729                        userId);
3730            }
3731        }
3732        return null;
3733    }
3734
3735    @Override
3736    public String[] getSystemSharedLibraryNames() {
3737        Set<String> libSet;
3738        synchronized (mPackages) {
3739            libSet = mSharedLibraries.keySet();
3740            int size = libSet.size();
3741            if (size > 0) {
3742                String[] libs = new String[size];
3743                libSet.toArray(libs);
3744                return libs;
3745            }
3746        }
3747        return null;
3748    }
3749
3750    @Override
3751    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3752        synchronized (mPackages) {
3753            return mServicesSystemSharedLibraryPackageName;
3754        }
3755    }
3756
3757    @Override
3758    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3759        synchronized (mPackages) {
3760            return mSharedSystemSharedLibraryPackageName;
3761        }
3762    }
3763
3764    @Override
3765    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3766        synchronized (mPackages) {
3767            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3768
3769            final FeatureInfo fi = new FeatureInfo();
3770            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3771                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3772            res.add(fi);
3773
3774            return new ParceledListSlice<>(res);
3775        }
3776    }
3777
3778    @Override
3779    public boolean hasSystemFeature(String name, int version) {
3780        synchronized (mPackages) {
3781            final FeatureInfo feat = mAvailableFeatures.get(name);
3782            if (feat == null) {
3783                return false;
3784            } else {
3785                return feat.version >= version;
3786            }
3787        }
3788    }
3789
3790    @Override
3791    public int checkPermission(String permName, String pkgName, int userId) {
3792        if (!sUserManager.exists(userId)) {
3793            return PackageManager.PERMISSION_DENIED;
3794        }
3795
3796        synchronized (mPackages) {
3797            final PackageParser.Package p = mPackages.get(pkgName);
3798            if (p != null && p.mExtras != null) {
3799                final PackageSetting ps = (PackageSetting) p.mExtras;
3800                final PermissionsState permissionsState = ps.getPermissionsState();
3801                if (permissionsState.hasPermission(permName, userId)) {
3802                    return PackageManager.PERMISSION_GRANTED;
3803                }
3804                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3805                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3806                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3807                    return PackageManager.PERMISSION_GRANTED;
3808                }
3809            }
3810        }
3811
3812        return PackageManager.PERMISSION_DENIED;
3813    }
3814
3815    @Override
3816    public int checkUidPermission(String permName, int uid) {
3817        final int userId = UserHandle.getUserId(uid);
3818
3819        if (!sUserManager.exists(userId)) {
3820            return PackageManager.PERMISSION_DENIED;
3821        }
3822
3823        synchronized (mPackages) {
3824            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3825            if (obj != null) {
3826                final SettingBase ps = (SettingBase) obj;
3827                final PermissionsState permissionsState = ps.getPermissionsState();
3828                if (permissionsState.hasPermission(permName, userId)) {
3829                    return PackageManager.PERMISSION_GRANTED;
3830                }
3831                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3832                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3833                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3834                    return PackageManager.PERMISSION_GRANTED;
3835                }
3836            } else {
3837                ArraySet<String> perms = mSystemPermissions.get(uid);
3838                if (perms != null) {
3839                    if (perms.contains(permName)) {
3840                        return PackageManager.PERMISSION_GRANTED;
3841                    }
3842                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3843                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3844                        return PackageManager.PERMISSION_GRANTED;
3845                    }
3846                }
3847            }
3848        }
3849
3850        return PackageManager.PERMISSION_DENIED;
3851    }
3852
3853    @Override
3854    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3855        if (UserHandle.getCallingUserId() != userId) {
3856            mContext.enforceCallingPermission(
3857                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3858                    "isPermissionRevokedByPolicy for user " + userId);
3859        }
3860
3861        if (checkPermission(permission, packageName, userId)
3862                == PackageManager.PERMISSION_GRANTED) {
3863            return false;
3864        }
3865
3866        final long identity = Binder.clearCallingIdentity();
3867        try {
3868            final int flags = getPermissionFlags(permission, packageName, userId);
3869            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3870        } finally {
3871            Binder.restoreCallingIdentity(identity);
3872        }
3873    }
3874
3875    @Override
3876    public String getPermissionControllerPackageName() {
3877        synchronized (mPackages) {
3878            return mRequiredInstallerPackage;
3879        }
3880    }
3881
3882    /**
3883     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3884     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3885     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3886     * @param message the message to log on security exception
3887     */
3888    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3889            boolean checkShell, String message) {
3890        if (userId < 0) {
3891            throw new IllegalArgumentException("Invalid userId " + userId);
3892        }
3893        if (checkShell) {
3894            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3895        }
3896        if (userId == UserHandle.getUserId(callingUid)) return;
3897        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3898            if (requireFullPermission) {
3899                mContext.enforceCallingOrSelfPermission(
3900                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3901            } else {
3902                try {
3903                    mContext.enforceCallingOrSelfPermission(
3904                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3905                } catch (SecurityException se) {
3906                    mContext.enforceCallingOrSelfPermission(
3907                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3908                }
3909            }
3910        }
3911    }
3912
3913    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3914        if (callingUid == Process.SHELL_UID) {
3915            if (userHandle >= 0
3916                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3917                throw new SecurityException("Shell does not have permission to access user "
3918                        + userHandle);
3919            } else if (userHandle < 0) {
3920                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3921                        + Debug.getCallers(3));
3922            }
3923        }
3924    }
3925
3926    private BasePermission findPermissionTreeLP(String permName) {
3927        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3928            if (permName.startsWith(bp.name) &&
3929                    permName.length() > bp.name.length() &&
3930                    permName.charAt(bp.name.length()) == '.') {
3931                return bp;
3932            }
3933        }
3934        return null;
3935    }
3936
3937    private BasePermission checkPermissionTreeLP(String permName) {
3938        if (permName != null) {
3939            BasePermission bp = findPermissionTreeLP(permName);
3940            if (bp != null) {
3941                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3942                    return bp;
3943                }
3944                throw new SecurityException("Calling uid "
3945                        + Binder.getCallingUid()
3946                        + " is not allowed to add to permission tree "
3947                        + bp.name + " owned by uid " + bp.uid);
3948            }
3949        }
3950        throw new SecurityException("No permission tree found for " + permName);
3951    }
3952
3953    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3954        if (s1 == null) {
3955            return s2 == null;
3956        }
3957        if (s2 == null) {
3958            return false;
3959        }
3960        if (s1.getClass() != s2.getClass()) {
3961            return false;
3962        }
3963        return s1.equals(s2);
3964    }
3965
3966    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3967        if (pi1.icon != pi2.icon) return false;
3968        if (pi1.logo != pi2.logo) return false;
3969        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3970        if (!compareStrings(pi1.name, pi2.name)) return false;
3971        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3972        // We'll take care of setting this one.
3973        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3974        // These are not currently stored in settings.
3975        //if (!compareStrings(pi1.group, pi2.group)) return false;
3976        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3977        //if (pi1.labelRes != pi2.labelRes) return false;
3978        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3979        return true;
3980    }
3981
3982    int permissionInfoFootprint(PermissionInfo info) {
3983        int size = info.name.length();
3984        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3985        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3986        return size;
3987    }
3988
3989    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3990        int size = 0;
3991        for (BasePermission perm : mSettings.mPermissions.values()) {
3992            if (perm.uid == tree.uid) {
3993                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3994            }
3995        }
3996        return size;
3997    }
3998
3999    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4000        // We calculate the max size of permissions defined by this uid and throw
4001        // if that plus the size of 'info' would exceed our stated maximum.
4002        if (tree.uid != Process.SYSTEM_UID) {
4003            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4004            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4005                throw new SecurityException("Permission tree size cap exceeded");
4006            }
4007        }
4008    }
4009
4010    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4011        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4012            throw new SecurityException("Label must be specified in permission");
4013        }
4014        BasePermission tree = checkPermissionTreeLP(info.name);
4015        BasePermission bp = mSettings.mPermissions.get(info.name);
4016        boolean added = bp == null;
4017        boolean changed = true;
4018        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4019        if (added) {
4020            enforcePermissionCapLocked(info, tree);
4021            bp = new BasePermission(info.name, tree.sourcePackage,
4022                    BasePermission.TYPE_DYNAMIC);
4023        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4024            throw new SecurityException(
4025                    "Not allowed to modify non-dynamic permission "
4026                    + info.name);
4027        } else {
4028            if (bp.protectionLevel == fixedLevel
4029                    && bp.perm.owner.equals(tree.perm.owner)
4030                    && bp.uid == tree.uid
4031                    && comparePermissionInfos(bp.perm.info, info)) {
4032                changed = false;
4033            }
4034        }
4035        bp.protectionLevel = fixedLevel;
4036        info = new PermissionInfo(info);
4037        info.protectionLevel = fixedLevel;
4038        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4039        bp.perm.info.packageName = tree.perm.info.packageName;
4040        bp.uid = tree.uid;
4041        if (added) {
4042            mSettings.mPermissions.put(info.name, bp);
4043        }
4044        if (changed) {
4045            if (!async) {
4046                mSettings.writeLPr();
4047            } else {
4048                scheduleWriteSettingsLocked();
4049            }
4050        }
4051        return added;
4052    }
4053
4054    @Override
4055    public boolean addPermission(PermissionInfo info) {
4056        synchronized (mPackages) {
4057            return addPermissionLocked(info, false);
4058        }
4059    }
4060
4061    @Override
4062    public boolean addPermissionAsync(PermissionInfo info) {
4063        synchronized (mPackages) {
4064            return addPermissionLocked(info, true);
4065        }
4066    }
4067
4068    @Override
4069    public void removePermission(String name) {
4070        synchronized (mPackages) {
4071            checkPermissionTreeLP(name);
4072            BasePermission bp = mSettings.mPermissions.get(name);
4073            if (bp != null) {
4074                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4075                    throw new SecurityException(
4076                            "Not allowed to modify non-dynamic permission "
4077                            + name);
4078                }
4079                mSettings.mPermissions.remove(name);
4080                mSettings.writeLPr();
4081            }
4082        }
4083    }
4084
4085    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4086            BasePermission bp) {
4087        int index = pkg.requestedPermissions.indexOf(bp.name);
4088        if (index == -1) {
4089            throw new SecurityException("Package " + pkg.packageName
4090                    + " has not requested permission " + bp.name);
4091        }
4092        if (!bp.isRuntime() && !bp.isDevelopment()) {
4093            throw new SecurityException("Permission " + bp.name
4094                    + " is not a changeable permission type");
4095        }
4096    }
4097
4098    @Override
4099    public void grantRuntimePermission(String packageName, String name, final int userId) {
4100        if (!sUserManager.exists(userId)) {
4101            Log.e(TAG, "No such user:" + userId);
4102            return;
4103        }
4104
4105        mContext.enforceCallingOrSelfPermission(
4106                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4107                "grantRuntimePermission");
4108
4109        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4110                true /* requireFullPermission */, true /* checkShell */,
4111                "grantRuntimePermission");
4112
4113        final int uid;
4114        final SettingBase sb;
4115
4116        synchronized (mPackages) {
4117            final PackageParser.Package pkg = mPackages.get(packageName);
4118            if (pkg == null) {
4119                throw new IllegalArgumentException("Unknown package: " + packageName);
4120            }
4121
4122            final BasePermission bp = mSettings.mPermissions.get(name);
4123            if (bp == null) {
4124                throw new IllegalArgumentException("Unknown permission: " + name);
4125            }
4126
4127            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4128
4129            // If a permission review is required for legacy apps we represent
4130            // their permissions as always granted runtime ones since we need
4131            // to keep the review required permission flag per user while an
4132            // install permission's state is shared across all users.
4133            if (Build.PERMISSIONS_REVIEW_REQUIRED
4134                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4135                    && bp.isRuntime()) {
4136                return;
4137            }
4138
4139            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4140            sb = (SettingBase) pkg.mExtras;
4141            if (sb == null) {
4142                throw new IllegalArgumentException("Unknown package: " + packageName);
4143            }
4144
4145            final PermissionsState permissionsState = sb.getPermissionsState();
4146
4147            final int flags = permissionsState.getPermissionFlags(name, userId);
4148            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4149                throw new SecurityException("Cannot grant system fixed permission "
4150                        + name + " for package " + packageName);
4151            }
4152
4153            if (bp.isDevelopment()) {
4154                // Development permissions must be handled specially, since they are not
4155                // normal runtime permissions.  For now they apply to all users.
4156                if (permissionsState.grantInstallPermission(bp) !=
4157                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4158                    scheduleWriteSettingsLocked();
4159                }
4160                return;
4161            }
4162
4163            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4164                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4165                return;
4166            }
4167
4168            final int result = permissionsState.grantRuntimePermission(bp, userId);
4169            switch (result) {
4170                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4171                    return;
4172                }
4173
4174                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4175                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4176                    mHandler.post(new Runnable() {
4177                        @Override
4178                        public void run() {
4179                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4180                        }
4181                    });
4182                }
4183                break;
4184            }
4185
4186            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4187
4188            // Not critical if that is lost - app has to request again.
4189            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4190        }
4191
4192        // Only need to do this if user is initialized. Otherwise it's a new user
4193        // and there are no processes running as the user yet and there's no need
4194        // to make an expensive call to remount processes for the changed permissions.
4195        if (READ_EXTERNAL_STORAGE.equals(name)
4196                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4197            final long token = Binder.clearCallingIdentity();
4198            try {
4199                if (sUserManager.isInitialized(userId)) {
4200                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4201                            MountServiceInternal.class);
4202                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4203                }
4204            } finally {
4205                Binder.restoreCallingIdentity(token);
4206            }
4207        }
4208    }
4209
4210    @Override
4211    public void revokeRuntimePermission(String packageName, String name, int userId) {
4212        if (!sUserManager.exists(userId)) {
4213            Log.e(TAG, "No such user:" + userId);
4214            return;
4215        }
4216
4217        mContext.enforceCallingOrSelfPermission(
4218                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4219                "revokeRuntimePermission");
4220
4221        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4222                true /* requireFullPermission */, true /* checkShell */,
4223                "revokeRuntimePermission");
4224
4225        final int appId;
4226
4227        synchronized (mPackages) {
4228            final PackageParser.Package pkg = mPackages.get(packageName);
4229            if (pkg == null) {
4230                throw new IllegalArgumentException("Unknown package: " + packageName);
4231            }
4232
4233            final BasePermission bp = mSettings.mPermissions.get(name);
4234            if (bp == null) {
4235                throw new IllegalArgumentException("Unknown permission: " + name);
4236            }
4237
4238            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4239
4240            // If a permission review is required for legacy apps we represent
4241            // their permissions as always granted runtime ones since we need
4242            // to keep the review required permission flag per user while an
4243            // install permission's state is shared across all users.
4244            if (Build.PERMISSIONS_REVIEW_REQUIRED
4245                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4246                    && bp.isRuntime()) {
4247                return;
4248            }
4249
4250            SettingBase sb = (SettingBase) pkg.mExtras;
4251            if (sb == null) {
4252                throw new IllegalArgumentException("Unknown package: " + packageName);
4253            }
4254
4255            final PermissionsState permissionsState = sb.getPermissionsState();
4256
4257            final int flags = permissionsState.getPermissionFlags(name, userId);
4258            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4259                throw new SecurityException("Cannot revoke system fixed permission "
4260                        + name + " for package " + packageName);
4261            }
4262
4263            if (bp.isDevelopment()) {
4264                // Development permissions must be handled specially, since they are not
4265                // normal runtime permissions.  For now they apply to all users.
4266                if (permissionsState.revokeInstallPermission(bp) !=
4267                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4268                    scheduleWriteSettingsLocked();
4269                }
4270                return;
4271            }
4272
4273            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4274                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4275                return;
4276            }
4277
4278            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4279
4280            // Critical, after this call app should never have the permission.
4281            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4282
4283            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4284        }
4285
4286        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4287    }
4288
4289    @Override
4290    public void resetRuntimePermissions() {
4291        mContext.enforceCallingOrSelfPermission(
4292                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4293                "revokeRuntimePermission");
4294
4295        int callingUid = Binder.getCallingUid();
4296        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4297            mContext.enforceCallingOrSelfPermission(
4298                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4299                    "resetRuntimePermissions");
4300        }
4301
4302        synchronized (mPackages) {
4303            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4304            for (int userId : UserManagerService.getInstance().getUserIds()) {
4305                final int packageCount = mPackages.size();
4306                for (int i = 0; i < packageCount; i++) {
4307                    PackageParser.Package pkg = mPackages.valueAt(i);
4308                    if (!(pkg.mExtras instanceof PackageSetting)) {
4309                        continue;
4310                    }
4311                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4312                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4313                }
4314            }
4315        }
4316    }
4317
4318    @Override
4319    public int getPermissionFlags(String name, String packageName, int userId) {
4320        if (!sUserManager.exists(userId)) {
4321            return 0;
4322        }
4323
4324        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4325
4326        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4327                true /* requireFullPermission */, false /* checkShell */,
4328                "getPermissionFlags");
4329
4330        synchronized (mPackages) {
4331            final PackageParser.Package pkg = mPackages.get(packageName);
4332            if (pkg == null) {
4333                return 0;
4334            }
4335
4336            final BasePermission bp = mSettings.mPermissions.get(name);
4337            if (bp == null) {
4338                return 0;
4339            }
4340
4341            SettingBase sb = (SettingBase) pkg.mExtras;
4342            if (sb == null) {
4343                return 0;
4344            }
4345
4346            PermissionsState permissionsState = sb.getPermissionsState();
4347            return permissionsState.getPermissionFlags(name, userId);
4348        }
4349    }
4350
4351    @Override
4352    public void updatePermissionFlags(String name, String packageName, int flagMask,
4353            int flagValues, int userId) {
4354        if (!sUserManager.exists(userId)) {
4355            return;
4356        }
4357
4358        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4359
4360        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4361                true /* requireFullPermission */, true /* checkShell */,
4362                "updatePermissionFlags");
4363
4364        // Only the system can change these flags and nothing else.
4365        if (getCallingUid() != Process.SYSTEM_UID) {
4366            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4367            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4368            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4369            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4370            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4371        }
4372
4373        synchronized (mPackages) {
4374            final PackageParser.Package pkg = mPackages.get(packageName);
4375            if (pkg == null) {
4376                throw new IllegalArgumentException("Unknown package: " + packageName);
4377            }
4378
4379            final BasePermission bp = mSettings.mPermissions.get(name);
4380            if (bp == null) {
4381                throw new IllegalArgumentException("Unknown permission: " + name);
4382            }
4383
4384            SettingBase sb = (SettingBase) pkg.mExtras;
4385            if (sb == null) {
4386                throw new IllegalArgumentException("Unknown package: " + packageName);
4387            }
4388
4389            PermissionsState permissionsState = sb.getPermissionsState();
4390
4391            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4392
4393            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4394                // Install and runtime permissions are stored in different places,
4395                // so figure out what permission changed and persist the change.
4396                if (permissionsState.getInstallPermissionState(name) != null) {
4397                    scheduleWriteSettingsLocked();
4398                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4399                        || hadState) {
4400                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4401                }
4402            }
4403        }
4404    }
4405
4406    /**
4407     * Update the permission flags for all packages and runtime permissions of a user in order
4408     * to allow device or profile owner to remove POLICY_FIXED.
4409     */
4410    @Override
4411    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4412        if (!sUserManager.exists(userId)) {
4413            return;
4414        }
4415
4416        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4417
4418        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4419                true /* requireFullPermission */, true /* checkShell */,
4420                "updatePermissionFlagsForAllApps");
4421
4422        // Only the system can change system fixed flags.
4423        if (getCallingUid() != Process.SYSTEM_UID) {
4424            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4425            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4426        }
4427
4428        synchronized (mPackages) {
4429            boolean changed = false;
4430            final int packageCount = mPackages.size();
4431            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4432                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4433                SettingBase sb = (SettingBase) pkg.mExtras;
4434                if (sb == null) {
4435                    continue;
4436                }
4437                PermissionsState permissionsState = sb.getPermissionsState();
4438                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4439                        userId, flagMask, flagValues);
4440            }
4441            if (changed) {
4442                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4443            }
4444        }
4445    }
4446
4447    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4448        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4449                != PackageManager.PERMISSION_GRANTED
4450            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4451                != PackageManager.PERMISSION_GRANTED) {
4452            throw new SecurityException(message + " requires "
4453                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4454                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4455        }
4456    }
4457
4458    @Override
4459    public boolean shouldShowRequestPermissionRationale(String permissionName,
4460            String packageName, int userId) {
4461        if (UserHandle.getCallingUserId() != userId) {
4462            mContext.enforceCallingPermission(
4463                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4464                    "canShowRequestPermissionRationale for user " + userId);
4465        }
4466
4467        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4468        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4469            return false;
4470        }
4471
4472        if (checkPermission(permissionName, packageName, userId)
4473                == PackageManager.PERMISSION_GRANTED) {
4474            return false;
4475        }
4476
4477        final int flags;
4478
4479        final long identity = Binder.clearCallingIdentity();
4480        try {
4481            flags = getPermissionFlags(permissionName,
4482                    packageName, userId);
4483        } finally {
4484            Binder.restoreCallingIdentity(identity);
4485        }
4486
4487        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4488                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4489                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4490
4491        if ((flags & fixedFlags) != 0) {
4492            return false;
4493        }
4494
4495        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4496    }
4497
4498    @Override
4499    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4500        mContext.enforceCallingOrSelfPermission(
4501                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4502                "addOnPermissionsChangeListener");
4503
4504        synchronized (mPackages) {
4505            mOnPermissionChangeListeners.addListenerLocked(listener);
4506        }
4507    }
4508
4509    @Override
4510    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4511        synchronized (mPackages) {
4512            mOnPermissionChangeListeners.removeListenerLocked(listener);
4513        }
4514    }
4515
4516    @Override
4517    public boolean isProtectedBroadcast(String actionName) {
4518        synchronized (mPackages) {
4519            if (mProtectedBroadcasts.contains(actionName)) {
4520                return true;
4521            } else if (actionName != null) {
4522                // TODO: remove these terrible hacks
4523                if (actionName.startsWith("android.net.netmon.lingerExpired")
4524                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4525                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4526                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4527                    return true;
4528                }
4529            }
4530        }
4531        return false;
4532    }
4533
4534    @Override
4535    public int checkSignatures(String pkg1, String pkg2) {
4536        synchronized (mPackages) {
4537            final PackageParser.Package p1 = mPackages.get(pkg1);
4538            final PackageParser.Package p2 = mPackages.get(pkg2);
4539            if (p1 == null || p1.mExtras == null
4540                    || p2 == null || p2.mExtras == null) {
4541                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4542            }
4543            return compareSignatures(p1.mSignatures, p2.mSignatures);
4544        }
4545    }
4546
4547    @Override
4548    public int checkUidSignatures(int uid1, int uid2) {
4549        // Map to base uids.
4550        uid1 = UserHandle.getAppId(uid1);
4551        uid2 = UserHandle.getAppId(uid2);
4552        // reader
4553        synchronized (mPackages) {
4554            Signature[] s1;
4555            Signature[] s2;
4556            Object obj = mSettings.getUserIdLPr(uid1);
4557            if (obj != null) {
4558                if (obj instanceof SharedUserSetting) {
4559                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4560                } else if (obj instanceof PackageSetting) {
4561                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4562                } else {
4563                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4564                }
4565            } else {
4566                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4567            }
4568            obj = mSettings.getUserIdLPr(uid2);
4569            if (obj != null) {
4570                if (obj instanceof SharedUserSetting) {
4571                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4572                } else if (obj instanceof PackageSetting) {
4573                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4574                } else {
4575                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4576                }
4577            } else {
4578                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4579            }
4580            return compareSignatures(s1, s2);
4581        }
4582    }
4583
4584    /**
4585     * This method should typically only be used when granting or revoking
4586     * permissions, since the app may immediately restart after this call.
4587     * <p>
4588     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4589     * guard your work against the app being relaunched.
4590     */
4591    private void killUid(int appId, int userId, String reason) {
4592        final long identity = Binder.clearCallingIdentity();
4593        try {
4594            IActivityManager am = ActivityManagerNative.getDefault();
4595            if (am != null) {
4596                try {
4597                    am.killUid(appId, userId, reason);
4598                } catch (RemoteException e) {
4599                    /* ignore - same process */
4600                }
4601            }
4602        } finally {
4603            Binder.restoreCallingIdentity(identity);
4604        }
4605    }
4606
4607    /**
4608     * Compares two sets of signatures. Returns:
4609     * <br />
4610     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4611     * <br />
4612     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4613     * <br />
4614     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4615     * <br />
4616     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4617     * <br />
4618     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4619     */
4620    static int compareSignatures(Signature[] s1, Signature[] s2) {
4621        if (s1 == null) {
4622            return s2 == null
4623                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4624                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4625        }
4626
4627        if (s2 == null) {
4628            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4629        }
4630
4631        if (s1.length != s2.length) {
4632            return PackageManager.SIGNATURE_NO_MATCH;
4633        }
4634
4635        // Since both signature sets are of size 1, we can compare without HashSets.
4636        if (s1.length == 1) {
4637            return s1[0].equals(s2[0]) ?
4638                    PackageManager.SIGNATURE_MATCH :
4639                    PackageManager.SIGNATURE_NO_MATCH;
4640        }
4641
4642        ArraySet<Signature> set1 = new ArraySet<Signature>();
4643        for (Signature sig : s1) {
4644            set1.add(sig);
4645        }
4646        ArraySet<Signature> set2 = new ArraySet<Signature>();
4647        for (Signature sig : s2) {
4648            set2.add(sig);
4649        }
4650        // Make sure s2 contains all signatures in s1.
4651        if (set1.equals(set2)) {
4652            return PackageManager.SIGNATURE_MATCH;
4653        }
4654        return PackageManager.SIGNATURE_NO_MATCH;
4655    }
4656
4657    /**
4658     * If the database version for this type of package (internal storage or
4659     * external storage) is less than the version where package signatures
4660     * were updated, return true.
4661     */
4662    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4663        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4664        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4665    }
4666
4667    /**
4668     * Used for backward compatibility to make sure any packages with
4669     * certificate chains get upgraded to the new style. {@code existingSigs}
4670     * will be in the old format (since they were stored on disk from before the
4671     * system upgrade) and {@code scannedSigs} will be in the newer format.
4672     */
4673    private int compareSignaturesCompat(PackageSignatures existingSigs,
4674            PackageParser.Package scannedPkg) {
4675        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4676            return PackageManager.SIGNATURE_NO_MATCH;
4677        }
4678
4679        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4680        for (Signature sig : existingSigs.mSignatures) {
4681            existingSet.add(sig);
4682        }
4683        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4684        for (Signature sig : scannedPkg.mSignatures) {
4685            try {
4686                Signature[] chainSignatures = sig.getChainSignatures();
4687                for (Signature chainSig : chainSignatures) {
4688                    scannedCompatSet.add(chainSig);
4689                }
4690            } catch (CertificateEncodingException e) {
4691                scannedCompatSet.add(sig);
4692            }
4693        }
4694        /*
4695         * Make sure the expanded scanned set contains all signatures in the
4696         * existing one.
4697         */
4698        if (scannedCompatSet.equals(existingSet)) {
4699            // Migrate the old signatures to the new scheme.
4700            existingSigs.assignSignatures(scannedPkg.mSignatures);
4701            // The new KeySets will be re-added later in the scanning process.
4702            synchronized (mPackages) {
4703                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4704            }
4705            return PackageManager.SIGNATURE_MATCH;
4706        }
4707        return PackageManager.SIGNATURE_NO_MATCH;
4708    }
4709
4710    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4711        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4712        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4713    }
4714
4715    private int compareSignaturesRecover(PackageSignatures existingSigs,
4716            PackageParser.Package scannedPkg) {
4717        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4718            return PackageManager.SIGNATURE_NO_MATCH;
4719        }
4720
4721        String msg = null;
4722        try {
4723            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4724                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4725                        + scannedPkg.packageName);
4726                return PackageManager.SIGNATURE_MATCH;
4727            }
4728        } catch (CertificateException e) {
4729            msg = e.getMessage();
4730        }
4731
4732        logCriticalInfo(Log.INFO,
4733                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4734        return PackageManager.SIGNATURE_NO_MATCH;
4735    }
4736
4737    @Override
4738    public List<String> getAllPackages() {
4739        synchronized (mPackages) {
4740            return new ArrayList<String>(mPackages.keySet());
4741        }
4742    }
4743
4744    @Override
4745    public String[] getPackagesForUid(int uid) {
4746        uid = UserHandle.getAppId(uid);
4747        // reader
4748        synchronized (mPackages) {
4749            Object obj = mSettings.getUserIdLPr(uid);
4750            if (obj instanceof SharedUserSetting) {
4751                final SharedUserSetting sus = (SharedUserSetting) obj;
4752                final int N = sus.packages.size();
4753                final String[] res = new String[N];
4754                final Iterator<PackageSetting> it = sus.packages.iterator();
4755                int i = 0;
4756                while (it.hasNext()) {
4757                    res[i++] = it.next().name;
4758                }
4759                return res;
4760            } else if (obj instanceof PackageSetting) {
4761                final PackageSetting ps = (PackageSetting) obj;
4762                return new String[] { ps.name };
4763            }
4764        }
4765        return null;
4766    }
4767
4768    @Override
4769    public String getNameForUid(int uid) {
4770        // reader
4771        synchronized (mPackages) {
4772            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4773            if (obj instanceof SharedUserSetting) {
4774                final SharedUserSetting sus = (SharedUserSetting) obj;
4775                return sus.name + ":" + sus.userId;
4776            } else if (obj instanceof PackageSetting) {
4777                final PackageSetting ps = (PackageSetting) obj;
4778                return ps.name;
4779            }
4780        }
4781        return null;
4782    }
4783
4784    @Override
4785    public int getUidForSharedUser(String sharedUserName) {
4786        if(sharedUserName == null) {
4787            return -1;
4788        }
4789        // reader
4790        synchronized (mPackages) {
4791            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4792            if (suid == null) {
4793                return -1;
4794            }
4795            return suid.userId;
4796        }
4797    }
4798
4799    @Override
4800    public int getFlagsForUid(int uid) {
4801        synchronized (mPackages) {
4802            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4803            if (obj instanceof SharedUserSetting) {
4804                final SharedUserSetting sus = (SharedUserSetting) obj;
4805                return sus.pkgFlags;
4806            } else if (obj instanceof PackageSetting) {
4807                final PackageSetting ps = (PackageSetting) obj;
4808                return ps.pkgFlags;
4809            }
4810        }
4811        return 0;
4812    }
4813
4814    @Override
4815    public int getPrivateFlagsForUid(int uid) {
4816        synchronized (mPackages) {
4817            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4818            if (obj instanceof SharedUserSetting) {
4819                final SharedUserSetting sus = (SharedUserSetting) obj;
4820                return sus.pkgPrivateFlags;
4821            } else if (obj instanceof PackageSetting) {
4822                final PackageSetting ps = (PackageSetting) obj;
4823                return ps.pkgPrivateFlags;
4824            }
4825        }
4826        return 0;
4827    }
4828
4829    @Override
4830    public boolean isUidPrivileged(int uid) {
4831        uid = UserHandle.getAppId(uid);
4832        // reader
4833        synchronized (mPackages) {
4834            Object obj = mSettings.getUserIdLPr(uid);
4835            if (obj instanceof SharedUserSetting) {
4836                final SharedUserSetting sus = (SharedUserSetting) obj;
4837                final Iterator<PackageSetting> it = sus.packages.iterator();
4838                while (it.hasNext()) {
4839                    if (it.next().isPrivileged()) {
4840                        return true;
4841                    }
4842                }
4843            } else if (obj instanceof PackageSetting) {
4844                final PackageSetting ps = (PackageSetting) obj;
4845                return ps.isPrivileged();
4846            }
4847        }
4848        return false;
4849    }
4850
4851    @Override
4852    public String[] getAppOpPermissionPackages(String permissionName) {
4853        synchronized (mPackages) {
4854            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4855            if (pkgs == null) {
4856                return null;
4857            }
4858            return pkgs.toArray(new String[pkgs.size()]);
4859        }
4860    }
4861
4862    @Override
4863    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4864            int flags, int userId) {
4865        try {
4866            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4867
4868            if (!sUserManager.exists(userId)) return null;
4869            flags = updateFlagsForResolve(flags, userId, intent);
4870            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4871                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4872
4873            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4874            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4875                    flags, userId);
4876            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4877
4878            final ResolveInfo bestChoice =
4879                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4880
4881            if (isEphemeralAllowed(intent, query, userId)) {
4882                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4883                final EphemeralResolveInfo ai =
4884                        getEphemeralResolveInfo(intent, resolvedType, userId);
4885                if (ai != null) {
4886                    if (DEBUG_EPHEMERAL) {
4887                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4888                    }
4889                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4890                    bestChoice.ephemeralResolveInfo = ai;
4891                }
4892                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4893            }
4894            return bestChoice;
4895        } finally {
4896            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4897        }
4898    }
4899
4900    @Override
4901    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4902            IntentFilter filter, int match, ComponentName activity) {
4903        final int userId = UserHandle.getCallingUserId();
4904        if (DEBUG_PREFERRED) {
4905            Log.v(TAG, "setLastChosenActivity intent=" + intent
4906                + " resolvedType=" + resolvedType
4907                + " flags=" + flags
4908                + " filter=" + filter
4909                + " match=" + match
4910                + " activity=" + activity);
4911            filter.dump(new PrintStreamPrinter(System.out), "    ");
4912        }
4913        intent.setComponent(null);
4914        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4915                userId);
4916        // Find any earlier preferred or last chosen entries and nuke them
4917        findPreferredActivity(intent, resolvedType,
4918                flags, query, 0, false, true, false, userId);
4919        // Add the new activity as the last chosen for this filter
4920        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4921                "Setting last chosen");
4922    }
4923
4924    @Override
4925    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4926        final int userId = UserHandle.getCallingUserId();
4927        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4928        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4929                userId);
4930        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4931                false, false, false, userId);
4932    }
4933
4934
4935    private boolean isEphemeralAllowed(
4936            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4937        // Short circuit and return early if possible.
4938        if (DISABLE_EPHEMERAL_APPS) {
4939            return false;
4940        }
4941        final int callingUser = UserHandle.getCallingUserId();
4942        if (callingUser != UserHandle.USER_SYSTEM) {
4943            return false;
4944        }
4945        if (mEphemeralResolverConnection == null) {
4946            return false;
4947        }
4948        if (intent.getComponent() != null) {
4949            return false;
4950        }
4951        if (intent.getPackage() != null) {
4952            return false;
4953        }
4954        final boolean isWebUri = hasWebURI(intent);
4955        if (!isWebUri) {
4956            return false;
4957        }
4958        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4959        synchronized (mPackages) {
4960            final int count = resolvedActivites.size();
4961            for (int n = 0; n < count; n++) {
4962                ResolveInfo info = resolvedActivites.get(n);
4963                String packageName = info.activityInfo.packageName;
4964                PackageSetting ps = mSettings.mPackages.get(packageName);
4965                if (ps != null) {
4966                    // Try to get the status from User settings first
4967                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4968                    int status = (int) (packedStatus >> 32);
4969                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4970                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4971                        if (DEBUG_EPHEMERAL) {
4972                            Slog.v(TAG, "DENY ephemeral apps;"
4973                                + " pkg: " + packageName + ", status: " + status);
4974                        }
4975                        return false;
4976                    }
4977                }
4978            }
4979        }
4980        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4981        return true;
4982    }
4983
4984    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4985            int userId) {
4986        MessageDigest digest = null;
4987        try {
4988            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4989        } catch (NoSuchAlgorithmException e) {
4990            // If we can't create a digest, ignore ephemeral apps.
4991            return null;
4992        }
4993
4994        final byte[] hostBytes = intent.getData().getHost().getBytes();
4995        final byte[] digestBytes = digest.digest(hostBytes);
4996        int shaPrefix =
4997                digestBytes[0] << 24
4998                | digestBytes[1] << 16
4999                | digestBytes[2] << 8
5000                | digestBytes[3] << 0;
5001        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
5002                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
5003        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
5004            // No hash prefix match; there are no ephemeral apps for this domain.
5005            return null;
5006        }
5007        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
5008            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
5009            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
5010                continue;
5011            }
5012            final List<IntentFilter> filters = ephemeralApplication.getFilters();
5013            // No filters; this should never happen.
5014            if (filters.isEmpty()) {
5015                continue;
5016            }
5017            // We have a domain match; resolve the filters to see if anything matches.
5018            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
5019            for (int j = filters.size() - 1; j >= 0; --j) {
5020                final EphemeralResolveIntentInfo intentInfo =
5021                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
5022                ephemeralResolver.addFilter(intentInfo);
5023            }
5024            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
5025                    intent, resolvedType, false /*defaultOnly*/, userId);
5026            if (!matchedResolveInfoList.isEmpty()) {
5027                return matchedResolveInfoList.get(0);
5028            }
5029        }
5030        // Hash or filter mis-match; no ephemeral apps for this domain.
5031        return null;
5032    }
5033
5034    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5035            int flags, List<ResolveInfo> query, int userId) {
5036        if (query != null) {
5037            final int N = query.size();
5038            if (N == 1) {
5039                return query.get(0);
5040            } else if (N > 1) {
5041                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5042                // If there is more than one activity with the same priority,
5043                // then let the user decide between them.
5044                ResolveInfo r0 = query.get(0);
5045                ResolveInfo r1 = query.get(1);
5046                if (DEBUG_INTENT_MATCHING || debug) {
5047                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5048                            + r1.activityInfo.name + "=" + r1.priority);
5049                }
5050                // If the first activity has a higher priority, or a different
5051                // default, then it is always desirable to pick it.
5052                if (r0.priority != r1.priority
5053                        || r0.preferredOrder != r1.preferredOrder
5054                        || r0.isDefault != r1.isDefault) {
5055                    return query.get(0);
5056                }
5057                // If we have saved a preference for a preferred activity for
5058                // this Intent, use that.
5059                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5060                        flags, query, r0.priority, true, false, debug, userId);
5061                if (ri != null) {
5062                    return ri;
5063                }
5064                ri = new ResolveInfo(mResolveInfo);
5065                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5066                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5067                // If all of the options come from the same package, show the application's
5068                // label and icon instead of the generic resolver's.
5069                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5070                // and then throw away the ResolveInfo itself, meaning that the caller loses
5071                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5072                // a fallback for this case; we only set the target package's resources on
5073                // the ResolveInfo, not the ActivityInfo.
5074                final String intentPackage = intent.getPackage();
5075                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5076                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5077                    ri.resolvePackageName = intentPackage;
5078                    if (userNeedsBadging(userId)) {
5079                        ri.noResourceId = true;
5080                    } else {
5081                        ri.icon = appi.icon;
5082                    }
5083                    ri.iconResourceId = appi.icon;
5084                    ri.labelRes = appi.labelRes;
5085                }
5086                ri.activityInfo.applicationInfo = new ApplicationInfo(
5087                        ri.activityInfo.applicationInfo);
5088                if (userId != 0) {
5089                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5090                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5091                }
5092                // Make sure that the resolver is displayable in car mode
5093                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5094                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5095                return ri;
5096            }
5097        }
5098        return null;
5099    }
5100
5101    /**
5102     * Return true if the given list is not empty and all of its contents have
5103     * an activityInfo with the given package name.
5104     */
5105    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5106        if (ArrayUtils.isEmpty(list)) {
5107            return false;
5108        }
5109        for (int i = 0, N = list.size(); i < N; i++) {
5110            final ResolveInfo ri = list.get(i);
5111            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5112            if (ai == null || !packageName.equals(ai.packageName)) {
5113                return false;
5114            }
5115        }
5116        return true;
5117    }
5118
5119    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5120            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5121        final int N = query.size();
5122        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5123                .get(userId);
5124        // Get the list of persistent preferred activities that handle the intent
5125        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5126        List<PersistentPreferredActivity> pprefs = ppir != null
5127                ? ppir.queryIntent(intent, resolvedType,
5128                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5129                : null;
5130        if (pprefs != null && pprefs.size() > 0) {
5131            final int M = pprefs.size();
5132            for (int i=0; i<M; i++) {
5133                final PersistentPreferredActivity ppa = pprefs.get(i);
5134                if (DEBUG_PREFERRED || debug) {
5135                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5136                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5137                            + "\n  component=" + ppa.mComponent);
5138                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5139                }
5140                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5141                        flags | MATCH_DISABLED_COMPONENTS, userId);
5142                if (DEBUG_PREFERRED || debug) {
5143                    Slog.v(TAG, "Found persistent preferred activity:");
5144                    if (ai != null) {
5145                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5146                    } else {
5147                        Slog.v(TAG, "  null");
5148                    }
5149                }
5150                if (ai == null) {
5151                    // This previously registered persistent preferred activity
5152                    // component is no longer known. Ignore it and do NOT remove it.
5153                    continue;
5154                }
5155                for (int j=0; j<N; j++) {
5156                    final ResolveInfo ri = query.get(j);
5157                    if (!ri.activityInfo.applicationInfo.packageName
5158                            .equals(ai.applicationInfo.packageName)) {
5159                        continue;
5160                    }
5161                    if (!ri.activityInfo.name.equals(ai.name)) {
5162                        continue;
5163                    }
5164                    //  Found a persistent preference that can handle the intent.
5165                    if (DEBUG_PREFERRED || debug) {
5166                        Slog.v(TAG, "Returning persistent preferred activity: " +
5167                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5168                    }
5169                    return ri;
5170                }
5171            }
5172        }
5173        return null;
5174    }
5175
5176    // TODO: handle preferred activities missing while user has amnesia
5177    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5178            List<ResolveInfo> query, int priority, boolean always,
5179            boolean removeMatches, boolean debug, int userId) {
5180        if (!sUserManager.exists(userId)) return null;
5181        flags = updateFlagsForResolve(flags, userId, intent);
5182        // writer
5183        synchronized (mPackages) {
5184            if (intent.getSelector() != null) {
5185                intent = intent.getSelector();
5186            }
5187            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5188
5189            // Try to find a matching persistent preferred activity.
5190            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5191                    debug, userId);
5192
5193            // If a persistent preferred activity matched, use it.
5194            if (pri != null) {
5195                return pri;
5196            }
5197
5198            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5199            // Get the list of preferred activities that handle the intent
5200            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5201            List<PreferredActivity> prefs = pir != null
5202                    ? pir.queryIntent(intent, resolvedType,
5203                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5204                    : null;
5205            if (prefs != null && prefs.size() > 0) {
5206                boolean changed = false;
5207                try {
5208                    // First figure out how good the original match set is.
5209                    // We will only allow preferred activities that came
5210                    // from the same match quality.
5211                    int match = 0;
5212
5213                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5214
5215                    final int N = query.size();
5216                    for (int j=0; j<N; j++) {
5217                        final ResolveInfo ri = query.get(j);
5218                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5219                                + ": 0x" + Integer.toHexString(match));
5220                        if (ri.match > match) {
5221                            match = ri.match;
5222                        }
5223                    }
5224
5225                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5226                            + Integer.toHexString(match));
5227
5228                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5229                    final int M = prefs.size();
5230                    for (int i=0; i<M; i++) {
5231                        final PreferredActivity pa = prefs.get(i);
5232                        if (DEBUG_PREFERRED || debug) {
5233                            Slog.v(TAG, "Checking PreferredActivity ds="
5234                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5235                                    + "\n  component=" + pa.mPref.mComponent);
5236                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5237                        }
5238                        if (pa.mPref.mMatch != match) {
5239                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5240                                    + Integer.toHexString(pa.mPref.mMatch));
5241                            continue;
5242                        }
5243                        // If it's not an "always" type preferred activity and that's what we're
5244                        // looking for, skip it.
5245                        if (always && !pa.mPref.mAlways) {
5246                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5247                            continue;
5248                        }
5249                        final ActivityInfo ai = getActivityInfo(
5250                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5251                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5252                                userId);
5253                        if (DEBUG_PREFERRED || debug) {
5254                            Slog.v(TAG, "Found preferred activity:");
5255                            if (ai != null) {
5256                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5257                            } else {
5258                                Slog.v(TAG, "  null");
5259                            }
5260                        }
5261                        if (ai == null) {
5262                            // This previously registered preferred activity
5263                            // component is no longer known.  Most likely an update
5264                            // to the app was installed and in the new version this
5265                            // component no longer exists.  Clean it up by removing
5266                            // it from the preferred activities list, and skip it.
5267                            Slog.w(TAG, "Removing dangling preferred activity: "
5268                                    + pa.mPref.mComponent);
5269                            pir.removeFilter(pa);
5270                            changed = true;
5271                            continue;
5272                        }
5273                        for (int j=0; j<N; j++) {
5274                            final ResolveInfo ri = query.get(j);
5275                            if (!ri.activityInfo.applicationInfo.packageName
5276                                    .equals(ai.applicationInfo.packageName)) {
5277                                continue;
5278                            }
5279                            if (!ri.activityInfo.name.equals(ai.name)) {
5280                                continue;
5281                            }
5282
5283                            if (removeMatches) {
5284                                pir.removeFilter(pa);
5285                                changed = true;
5286                                if (DEBUG_PREFERRED) {
5287                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5288                                }
5289                                break;
5290                            }
5291
5292                            // Okay we found a previously set preferred or last chosen app.
5293                            // If the result set is different from when this
5294                            // was created, we need to clear it and re-ask the
5295                            // user their preference, if we're looking for an "always" type entry.
5296                            if (always && !pa.mPref.sameSet(query)) {
5297                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5298                                        + intent + " type " + resolvedType);
5299                                if (DEBUG_PREFERRED) {
5300                                    Slog.v(TAG, "Removing preferred activity since set changed "
5301                                            + pa.mPref.mComponent);
5302                                }
5303                                pir.removeFilter(pa);
5304                                // Re-add the filter as a "last chosen" entry (!always)
5305                                PreferredActivity lastChosen = new PreferredActivity(
5306                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5307                                pir.addFilter(lastChosen);
5308                                changed = true;
5309                                return null;
5310                            }
5311
5312                            // Yay! Either the set matched or we're looking for the last chosen
5313                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5314                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5315                            return ri;
5316                        }
5317                    }
5318                } finally {
5319                    if (changed) {
5320                        if (DEBUG_PREFERRED) {
5321                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5322                        }
5323                        scheduleWritePackageRestrictionsLocked(userId);
5324                    }
5325                }
5326            }
5327        }
5328        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5329        return null;
5330    }
5331
5332    /*
5333     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5334     */
5335    @Override
5336    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5337            int targetUserId) {
5338        mContext.enforceCallingOrSelfPermission(
5339                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5340        List<CrossProfileIntentFilter> matches =
5341                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5342        if (matches != null) {
5343            int size = matches.size();
5344            for (int i = 0; i < size; i++) {
5345                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5346            }
5347        }
5348        if (hasWebURI(intent)) {
5349            // cross-profile app linking works only towards the parent.
5350            final UserInfo parent = getProfileParent(sourceUserId);
5351            synchronized(mPackages) {
5352                int flags = updateFlagsForResolve(0, parent.id, intent);
5353                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5354                        intent, resolvedType, flags, sourceUserId, parent.id);
5355                return xpDomainInfo != null;
5356            }
5357        }
5358        return false;
5359    }
5360
5361    private UserInfo getProfileParent(int userId) {
5362        final long identity = Binder.clearCallingIdentity();
5363        try {
5364            return sUserManager.getProfileParent(userId);
5365        } finally {
5366            Binder.restoreCallingIdentity(identity);
5367        }
5368    }
5369
5370    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5371            String resolvedType, int userId) {
5372        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5373        if (resolver != null) {
5374            return resolver.queryIntent(intent, resolvedType, false, userId);
5375        }
5376        return null;
5377    }
5378
5379    @Override
5380    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5381            String resolvedType, int flags, int userId) {
5382        try {
5383            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5384
5385            return new ParceledListSlice<>(
5386                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5387        } finally {
5388            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5389        }
5390    }
5391
5392    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5393            String resolvedType, int flags, int userId) {
5394        if (!sUserManager.exists(userId)) return Collections.emptyList();
5395        flags = updateFlagsForResolve(flags, userId, intent);
5396        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5397                false /* requireFullPermission */, false /* checkShell */,
5398                "query intent activities");
5399        ComponentName comp = intent.getComponent();
5400        if (comp == null) {
5401            if (intent.getSelector() != null) {
5402                intent = intent.getSelector();
5403                comp = intent.getComponent();
5404            }
5405        }
5406
5407        if (comp != null) {
5408            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5409            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5410            if (ai != null) {
5411                final ResolveInfo ri = new ResolveInfo();
5412                ri.activityInfo = ai;
5413                list.add(ri);
5414            }
5415            return list;
5416        }
5417
5418        // reader
5419        synchronized (mPackages) {
5420            final String pkgName = intent.getPackage();
5421            if (pkgName == null) {
5422                List<CrossProfileIntentFilter> matchingFilters =
5423                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5424                // Check for results that need to skip the current profile.
5425                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5426                        resolvedType, flags, userId);
5427                if (xpResolveInfo != null) {
5428                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5429                    result.add(xpResolveInfo);
5430                    return filterIfNotSystemUser(result, userId);
5431                }
5432
5433                // Check for results in the current profile.
5434                List<ResolveInfo> result = mActivities.queryIntent(
5435                        intent, resolvedType, flags, userId);
5436                result = filterIfNotSystemUser(result, userId);
5437
5438                // Check for cross profile results.
5439                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5440                xpResolveInfo = queryCrossProfileIntents(
5441                        matchingFilters, intent, resolvedType, flags, userId,
5442                        hasNonNegativePriorityResult);
5443                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5444                    boolean isVisibleToUser = filterIfNotSystemUser(
5445                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5446                    if (isVisibleToUser) {
5447                        result.add(xpResolveInfo);
5448                        Collections.sort(result, mResolvePrioritySorter);
5449                    }
5450                }
5451                if (hasWebURI(intent)) {
5452                    CrossProfileDomainInfo xpDomainInfo = null;
5453                    final UserInfo parent = getProfileParent(userId);
5454                    if (parent != null) {
5455                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5456                                flags, userId, parent.id);
5457                    }
5458                    if (xpDomainInfo != null) {
5459                        if (xpResolveInfo != null) {
5460                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5461                            // in the result.
5462                            result.remove(xpResolveInfo);
5463                        }
5464                        if (result.size() == 0) {
5465                            result.add(xpDomainInfo.resolveInfo);
5466                            return result;
5467                        }
5468                    } else if (result.size() <= 1) {
5469                        return result;
5470                    }
5471                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5472                            xpDomainInfo, userId);
5473                    Collections.sort(result, mResolvePrioritySorter);
5474                }
5475                return result;
5476            }
5477            final PackageParser.Package pkg = mPackages.get(pkgName);
5478            if (pkg != null) {
5479                return filterIfNotSystemUser(
5480                        mActivities.queryIntentForPackage(
5481                                intent, resolvedType, flags, pkg.activities, userId),
5482                        userId);
5483            }
5484            return new ArrayList<ResolveInfo>();
5485        }
5486    }
5487
5488    private static class CrossProfileDomainInfo {
5489        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5490        ResolveInfo resolveInfo;
5491        /* Best domain verification status of the activities found in the other profile */
5492        int bestDomainVerificationStatus;
5493    }
5494
5495    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5496            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5497        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5498                sourceUserId)) {
5499            return null;
5500        }
5501        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5502                resolvedType, flags, parentUserId);
5503
5504        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5505            return null;
5506        }
5507        CrossProfileDomainInfo result = null;
5508        int size = resultTargetUser.size();
5509        for (int i = 0; i < size; i++) {
5510            ResolveInfo riTargetUser = resultTargetUser.get(i);
5511            // Intent filter verification is only for filters that specify a host. So don't return
5512            // those that handle all web uris.
5513            if (riTargetUser.handleAllWebDataURI) {
5514                continue;
5515            }
5516            String packageName = riTargetUser.activityInfo.packageName;
5517            PackageSetting ps = mSettings.mPackages.get(packageName);
5518            if (ps == null) {
5519                continue;
5520            }
5521            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5522            int status = (int)(verificationState >> 32);
5523            if (result == null) {
5524                result = new CrossProfileDomainInfo();
5525                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5526                        sourceUserId, parentUserId);
5527                result.bestDomainVerificationStatus = status;
5528            } else {
5529                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5530                        result.bestDomainVerificationStatus);
5531            }
5532        }
5533        // Don't consider matches with status NEVER across profiles.
5534        if (result != null && result.bestDomainVerificationStatus
5535                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5536            return null;
5537        }
5538        return result;
5539    }
5540
5541    /**
5542     * Verification statuses are ordered from the worse to the best, except for
5543     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5544     */
5545    private int bestDomainVerificationStatus(int status1, int status2) {
5546        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5547            return status2;
5548        }
5549        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5550            return status1;
5551        }
5552        return (int) MathUtils.max(status1, status2);
5553    }
5554
5555    private boolean isUserEnabled(int userId) {
5556        long callingId = Binder.clearCallingIdentity();
5557        try {
5558            UserInfo userInfo = sUserManager.getUserInfo(userId);
5559            return userInfo != null && userInfo.isEnabled();
5560        } finally {
5561            Binder.restoreCallingIdentity(callingId);
5562        }
5563    }
5564
5565    /**
5566     * Filter out activities with systemUserOnly flag set, when current user is not System.
5567     *
5568     * @return filtered list
5569     */
5570    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5571        if (userId == UserHandle.USER_SYSTEM) {
5572            return resolveInfos;
5573        }
5574        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5575            ResolveInfo info = resolveInfos.get(i);
5576            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5577                resolveInfos.remove(i);
5578            }
5579        }
5580        return resolveInfos;
5581    }
5582
5583    /**
5584     * @param resolveInfos list of resolve infos in descending priority order
5585     * @return if the list contains a resolve info with non-negative priority
5586     */
5587    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5588        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5589    }
5590
5591    private static boolean hasWebURI(Intent intent) {
5592        if (intent.getData() == null) {
5593            return false;
5594        }
5595        final String scheme = intent.getScheme();
5596        if (TextUtils.isEmpty(scheme)) {
5597            return false;
5598        }
5599        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5600    }
5601
5602    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5603            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5604            int userId) {
5605        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5606
5607        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5608            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5609                    candidates.size());
5610        }
5611
5612        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5613        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5614        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5615        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5616        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5617        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5618
5619        synchronized (mPackages) {
5620            final int count = candidates.size();
5621            // First, try to use linked apps. Partition the candidates into four lists:
5622            // one for the final results, one for the "do not use ever", one for "undefined status"
5623            // and finally one for "browser app type".
5624            for (int n=0; n<count; n++) {
5625                ResolveInfo info = candidates.get(n);
5626                String packageName = info.activityInfo.packageName;
5627                PackageSetting ps = mSettings.mPackages.get(packageName);
5628                if (ps != null) {
5629                    // Add to the special match all list (Browser use case)
5630                    if (info.handleAllWebDataURI) {
5631                        matchAllList.add(info);
5632                        continue;
5633                    }
5634                    // Try to get the status from User settings first
5635                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5636                    int status = (int)(packedStatus >> 32);
5637                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5638                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5639                        if (DEBUG_DOMAIN_VERIFICATION) {
5640                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5641                                    + " : linkgen=" + linkGeneration);
5642                        }
5643                        // Use link-enabled generation as preferredOrder, i.e.
5644                        // prefer newly-enabled over earlier-enabled.
5645                        info.preferredOrder = linkGeneration;
5646                        alwaysList.add(info);
5647                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5648                        if (DEBUG_DOMAIN_VERIFICATION) {
5649                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5650                        }
5651                        neverList.add(info);
5652                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5653                        if (DEBUG_DOMAIN_VERIFICATION) {
5654                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5655                        }
5656                        alwaysAskList.add(info);
5657                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5658                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5659                        if (DEBUG_DOMAIN_VERIFICATION) {
5660                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5661                        }
5662                        undefinedList.add(info);
5663                    }
5664                }
5665            }
5666
5667            // We'll want to include browser possibilities in a few cases
5668            boolean includeBrowser = false;
5669
5670            // First try to add the "always" resolution(s) for the current user, if any
5671            if (alwaysList.size() > 0) {
5672                result.addAll(alwaysList);
5673            } else {
5674                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5675                result.addAll(undefinedList);
5676                // Maybe add one for the other profile.
5677                if (xpDomainInfo != null && (
5678                        xpDomainInfo.bestDomainVerificationStatus
5679                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5680                    result.add(xpDomainInfo.resolveInfo);
5681                }
5682                includeBrowser = true;
5683            }
5684
5685            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5686            // If there were 'always' entries their preferred order has been set, so we also
5687            // back that off to make the alternatives equivalent
5688            if (alwaysAskList.size() > 0) {
5689                for (ResolveInfo i : result) {
5690                    i.preferredOrder = 0;
5691                }
5692                result.addAll(alwaysAskList);
5693                includeBrowser = true;
5694            }
5695
5696            if (includeBrowser) {
5697                // Also add browsers (all of them or only the default one)
5698                if (DEBUG_DOMAIN_VERIFICATION) {
5699                    Slog.v(TAG, "   ...including browsers in candidate set");
5700                }
5701                if ((matchFlags & MATCH_ALL) != 0) {
5702                    result.addAll(matchAllList);
5703                } else {
5704                    // Browser/generic handling case.  If there's a default browser, go straight
5705                    // to that (but only if there is no other higher-priority match).
5706                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5707                    int maxMatchPrio = 0;
5708                    ResolveInfo defaultBrowserMatch = null;
5709                    final int numCandidates = matchAllList.size();
5710                    for (int n = 0; n < numCandidates; n++) {
5711                        ResolveInfo info = matchAllList.get(n);
5712                        // track the highest overall match priority...
5713                        if (info.priority > maxMatchPrio) {
5714                            maxMatchPrio = info.priority;
5715                        }
5716                        // ...and the highest-priority default browser match
5717                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5718                            if (defaultBrowserMatch == null
5719                                    || (defaultBrowserMatch.priority < info.priority)) {
5720                                if (debug) {
5721                                    Slog.v(TAG, "Considering default browser match " + info);
5722                                }
5723                                defaultBrowserMatch = info;
5724                            }
5725                        }
5726                    }
5727                    if (defaultBrowserMatch != null
5728                            && defaultBrowserMatch.priority >= maxMatchPrio
5729                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5730                    {
5731                        if (debug) {
5732                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5733                        }
5734                        result.add(defaultBrowserMatch);
5735                    } else {
5736                        result.addAll(matchAllList);
5737                    }
5738                }
5739
5740                // If there is nothing selected, add all candidates and remove the ones that the user
5741                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5742                if (result.size() == 0) {
5743                    result.addAll(candidates);
5744                    result.removeAll(neverList);
5745                }
5746            }
5747        }
5748        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5749            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5750                    result.size());
5751            for (ResolveInfo info : result) {
5752                Slog.v(TAG, "  + " + info.activityInfo);
5753            }
5754        }
5755        return result;
5756    }
5757
5758    // Returns a packed value as a long:
5759    //
5760    // high 'int'-sized word: link status: undefined/ask/never/always.
5761    // low 'int'-sized word: relative priority among 'always' results.
5762    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5763        long result = ps.getDomainVerificationStatusForUser(userId);
5764        // if none available, get the master status
5765        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5766            if (ps.getIntentFilterVerificationInfo() != null) {
5767                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5768            }
5769        }
5770        return result;
5771    }
5772
5773    private ResolveInfo querySkipCurrentProfileIntents(
5774            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5775            int flags, int sourceUserId) {
5776        if (matchingFilters != null) {
5777            int size = matchingFilters.size();
5778            for (int i = 0; i < size; i ++) {
5779                CrossProfileIntentFilter filter = matchingFilters.get(i);
5780                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5781                    // Checking if there are activities in the target user that can handle the
5782                    // intent.
5783                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5784                            resolvedType, flags, sourceUserId);
5785                    if (resolveInfo != null) {
5786                        return resolveInfo;
5787                    }
5788                }
5789            }
5790        }
5791        return null;
5792    }
5793
5794    // Return matching ResolveInfo in target user if any.
5795    private ResolveInfo queryCrossProfileIntents(
5796            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5797            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5798        if (matchingFilters != null) {
5799            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5800            // match the same intent. For performance reasons, it is better not to
5801            // run queryIntent twice for the same userId
5802            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5803            int size = matchingFilters.size();
5804            for (int i = 0; i < size; i++) {
5805                CrossProfileIntentFilter filter = matchingFilters.get(i);
5806                int targetUserId = filter.getTargetUserId();
5807                boolean skipCurrentProfile =
5808                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5809                boolean skipCurrentProfileIfNoMatchFound =
5810                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5811                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5812                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5813                    // Checking if there are activities in the target user that can handle the
5814                    // intent.
5815                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5816                            resolvedType, flags, sourceUserId);
5817                    if (resolveInfo != null) return resolveInfo;
5818                    alreadyTriedUserIds.put(targetUserId, true);
5819                }
5820            }
5821        }
5822        return null;
5823    }
5824
5825    /**
5826     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5827     * will forward the intent to the filter's target user.
5828     * Otherwise, returns null.
5829     */
5830    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5831            String resolvedType, int flags, int sourceUserId) {
5832        int targetUserId = filter.getTargetUserId();
5833        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5834                resolvedType, flags, targetUserId);
5835        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5836            // If all the matches in the target profile are suspended, return null.
5837            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5838                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5839                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5840                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5841                            targetUserId);
5842                }
5843            }
5844        }
5845        return null;
5846    }
5847
5848    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5849            int sourceUserId, int targetUserId) {
5850        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5851        long ident = Binder.clearCallingIdentity();
5852        boolean targetIsProfile;
5853        try {
5854            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5855        } finally {
5856            Binder.restoreCallingIdentity(ident);
5857        }
5858        String className;
5859        if (targetIsProfile) {
5860            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5861        } else {
5862            className = FORWARD_INTENT_TO_PARENT;
5863        }
5864        ComponentName forwardingActivityComponentName = new ComponentName(
5865                mAndroidApplication.packageName, className);
5866        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5867                sourceUserId);
5868        if (!targetIsProfile) {
5869            forwardingActivityInfo.showUserIcon = targetUserId;
5870            forwardingResolveInfo.noResourceId = true;
5871        }
5872        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5873        forwardingResolveInfo.priority = 0;
5874        forwardingResolveInfo.preferredOrder = 0;
5875        forwardingResolveInfo.match = 0;
5876        forwardingResolveInfo.isDefault = true;
5877        forwardingResolveInfo.filter = filter;
5878        forwardingResolveInfo.targetUserId = targetUserId;
5879        return forwardingResolveInfo;
5880    }
5881
5882    @Override
5883    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5884            Intent[] specifics, String[] specificTypes, Intent intent,
5885            String resolvedType, int flags, int userId) {
5886        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5887                specificTypes, intent, resolvedType, flags, userId));
5888    }
5889
5890    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5891            Intent[] specifics, String[] specificTypes, Intent intent,
5892            String resolvedType, int flags, int userId) {
5893        if (!sUserManager.exists(userId)) return Collections.emptyList();
5894        flags = updateFlagsForResolve(flags, userId, intent);
5895        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5896                false /* requireFullPermission */, false /* checkShell */,
5897                "query intent activity options");
5898        final String resultsAction = intent.getAction();
5899
5900        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5901                | PackageManager.GET_RESOLVED_FILTER, userId);
5902
5903        if (DEBUG_INTENT_MATCHING) {
5904            Log.v(TAG, "Query " + intent + ": " + results);
5905        }
5906
5907        int specificsPos = 0;
5908        int N;
5909
5910        // todo: note that the algorithm used here is O(N^2).  This
5911        // isn't a problem in our current environment, but if we start running
5912        // into situations where we have more than 5 or 10 matches then this
5913        // should probably be changed to something smarter...
5914
5915        // First we go through and resolve each of the specific items
5916        // that were supplied, taking care of removing any corresponding
5917        // duplicate items in the generic resolve list.
5918        if (specifics != null) {
5919            for (int i=0; i<specifics.length; i++) {
5920                final Intent sintent = specifics[i];
5921                if (sintent == null) {
5922                    continue;
5923                }
5924
5925                if (DEBUG_INTENT_MATCHING) {
5926                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5927                }
5928
5929                String action = sintent.getAction();
5930                if (resultsAction != null && resultsAction.equals(action)) {
5931                    // If this action was explicitly requested, then don't
5932                    // remove things that have it.
5933                    action = null;
5934                }
5935
5936                ResolveInfo ri = null;
5937                ActivityInfo ai = null;
5938
5939                ComponentName comp = sintent.getComponent();
5940                if (comp == null) {
5941                    ri = resolveIntent(
5942                        sintent,
5943                        specificTypes != null ? specificTypes[i] : null,
5944                            flags, userId);
5945                    if (ri == null) {
5946                        continue;
5947                    }
5948                    if (ri == mResolveInfo) {
5949                        // ACK!  Must do something better with this.
5950                    }
5951                    ai = ri.activityInfo;
5952                    comp = new ComponentName(ai.applicationInfo.packageName,
5953                            ai.name);
5954                } else {
5955                    ai = getActivityInfo(comp, flags, userId);
5956                    if (ai == null) {
5957                        continue;
5958                    }
5959                }
5960
5961                // Look for any generic query activities that are duplicates
5962                // of this specific one, and remove them from the results.
5963                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5964                N = results.size();
5965                int j;
5966                for (j=specificsPos; j<N; j++) {
5967                    ResolveInfo sri = results.get(j);
5968                    if ((sri.activityInfo.name.equals(comp.getClassName())
5969                            && sri.activityInfo.applicationInfo.packageName.equals(
5970                                    comp.getPackageName()))
5971                        || (action != null && sri.filter.matchAction(action))) {
5972                        results.remove(j);
5973                        if (DEBUG_INTENT_MATCHING) Log.v(
5974                            TAG, "Removing duplicate item from " + j
5975                            + " due to specific " + specificsPos);
5976                        if (ri == null) {
5977                            ri = sri;
5978                        }
5979                        j--;
5980                        N--;
5981                    }
5982                }
5983
5984                // Add this specific item to its proper place.
5985                if (ri == null) {
5986                    ri = new ResolveInfo();
5987                    ri.activityInfo = ai;
5988                }
5989                results.add(specificsPos, ri);
5990                ri.specificIndex = i;
5991                specificsPos++;
5992            }
5993        }
5994
5995        // Now we go through the remaining generic results and remove any
5996        // duplicate actions that are found here.
5997        N = results.size();
5998        for (int i=specificsPos; i<N-1; i++) {
5999            final ResolveInfo rii = results.get(i);
6000            if (rii.filter == null) {
6001                continue;
6002            }
6003
6004            // Iterate over all of the actions of this result's intent
6005            // filter...  typically this should be just one.
6006            final Iterator<String> it = rii.filter.actionsIterator();
6007            if (it == null) {
6008                continue;
6009            }
6010            while (it.hasNext()) {
6011                final String action = it.next();
6012                if (resultsAction != null && resultsAction.equals(action)) {
6013                    // If this action was explicitly requested, then don't
6014                    // remove things that have it.
6015                    continue;
6016                }
6017                for (int j=i+1; j<N; j++) {
6018                    final ResolveInfo rij = results.get(j);
6019                    if (rij.filter != null && rij.filter.hasAction(action)) {
6020                        results.remove(j);
6021                        if (DEBUG_INTENT_MATCHING) Log.v(
6022                            TAG, "Removing duplicate item from " + j
6023                            + " due to action " + action + " at " + i);
6024                        j--;
6025                        N--;
6026                    }
6027                }
6028            }
6029
6030            // If the caller didn't request filter information, drop it now
6031            // so we don't have to marshall/unmarshall it.
6032            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6033                rii.filter = null;
6034            }
6035        }
6036
6037        // Filter out the caller activity if so requested.
6038        if (caller != null) {
6039            N = results.size();
6040            for (int i=0; i<N; i++) {
6041                ActivityInfo ainfo = results.get(i).activityInfo;
6042                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6043                        && caller.getClassName().equals(ainfo.name)) {
6044                    results.remove(i);
6045                    break;
6046                }
6047            }
6048        }
6049
6050        // If the caller didn't request filter information,
6051        // drop them now so we don't have to
6052        // marshall/unmarshall it.
6053        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6054            N = results.size();
6055            for (int i=0; i<N; i++) {
6056                results.get(i).filter = null;
6057            }
6058        }
6059
6060        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6061        return results;
6062    }
6063
6064    @Override
6065    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6066            String resolvedType, int flags, int userId) {
6067        return new ParceledListSlice<>(
6068                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6069    }
6070
6071    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6072            String resolvedType, int flags, int userId) {
6073        if (!sUserManager.exists(userId)) return Collections.emptyList();
6074        flags = updateFlagsForResolve(flags, userId, intent);
6075        ComponentName comp = intent.getComponent();
6076        if (comp == null) {
6077            if (intent.getSelector() != null) {
6078                intent = intent.getSelector();
6079                comp = intent.getComponent();
6080            }
6081        }
6082        if (comp != null) {
6083            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6084            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6085            if (ai != null) {
6086                ResolveInfo ri = new ResolveInfo();
6087                ri.activityInfo = ai;
6088                list.add(ri);
6089            }
6090            return list;
6091        }
6092
6093        // reader
6094        synchronized (mPackages) {
6095            String pkgName = intent.getPackage();
6096            if (pkgName == null) {
6097                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6098            }
6099            final PackageParser.Package pkg = mPackages.get(pkgName);
6100            if (pkg != null) {
6101                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6102                        userId);
6103            }
6104            return Collections.emptyList();
6105        }
6106    }
6107
6108    @Override
6109    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6110        if (!sUserManager.exists(userId)) return null;
6111        flags = updateFlagsForResolve(flags, userId, intent);
6112        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6113        if (query != null) {
6114            if (query.size() >= 1) {
6115                // If there is more than one service with the same priority,
6116                // just arbitrarily pick the first one.
6117                return query.get(0);
6118            }
6119        }
6120        return null;
6121    }
6122
6123    @Override
6124    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6125            String resolvedType, int flags, int userId) {
6126        return new ParceledListSlice<>(
6127                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6128    }
6129
6130    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6131            String resolvedType, int flags, int userId) {
6132        if (!sUserManager.exists(userId)) return Collections.emptyList();
6133        flags = updateFlagsForResolve(flags, userId, intent);
6134        ComponentName comp = intent.getComponent();
6135        if (comp == null) {
6136            if (intent.getSelector() != null) {
6137                intent = intent.getSelector();
6138                comp = intent.getComponent();
6139            }
6140        }
6141        if (comp != null) {
6142            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6143            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6144            if (si != null) {
6145                final ResolveInfo ri = new ResolveInfo();
6146                ri.serviceInfo = si;
6147                list.add(ri);
6148            }
6149            return list;
6150        }
6151
6152        // reader
6153        synchronized (mPackages) {
6154            String pkgName = intent.getPackage();
6155            if (pkgName == null) {
6156                return mServices.queryIntent(intent, resolvedType, flags, userId);
6157            }
6158            final PackageParser.Package pkg = mPackages.get(pkgName);
6159            if (pkg != null) {
6160                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6161                        userId);
6162            }
6163            return Collections.emptyList();
6164        }
6165    }
6166
6167    @Override
6168    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6169            String resolvedType, int flags, int userId) {
6170        return new ParceledListSlice<>(
6171                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6172    }
6173
6174    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6175            Intent intent, String resolvedType, int flags, int userId) {
6176        if (!sUserManager.exists(userId)) return Collections.emptyList();
6177        flags = updateFlagsForResolve(flags, userId, intent);
6178        ComponentName comp = intent.getComponent();
6179        if (comp == null) {
6180            if (intent.getSelector() != null) {
6181                intent = intent.getSelector();
6182                comp = intent.getComponent();
6183            }
6184        }
6185        if (comp != null) {
6186            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6187            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6188            if (pi != null) {
6189                final ResolveInfo ri = new ResolveInfo();
6190                ri.providerInfo = pi;
6191                list.add(ri);
6192            }
6193            return list;
6194        }
6195
6196        // reader
6197        synchronized (mPackages) {
6198            String pkgName = intent.getPackage();
6199            if (pkgName == null) {
6200                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6201            }
6202            final PackageParser.Package pkg = mPackages.get(pkgName);
6203            if (pkg != null) {
6204                return mProviders.queryIntentForPackage(
6205                        intent, resolvedType, flags, pkg.providers, userId);
6206            }
6207            return Collections.emptyList();
6208        }
6209    }
6210
6211    @Override
6212    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6213        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6214        flags = updateFlagsForPackage(flags, userId, null);
6215        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6216        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6217                true /* requireFullPermission */, false /* checkShell */,
6218                "get installed packages");
6219
6220        // writer
6221        synchronized (mPackages) {
6222            ArrayList<PackageInfo> list;
6223            if (listUninstalled) {
6224                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6225                for (PackageSetting ps : mSettings.mPackages.values()) {
6226                    final PackageInfo pi;
6227                    if (ps.pkg != null) {
6228                        pi = generatePackageInfo(ps, flags, userId);
6229                    } else {
6230                        pi = generatePackageInfo(ps, flags, userId);
6231                    }
6232                    if (pi != null) {
6233                        list.add(pi);
6234                    }
6235                }
6236            } else {
6237                list = new ArrayList<PackageInfo>(mPackages.size());
6238                for (PackageParser.Package p : mPackages.values()) {
6239                    final PackageInfo pi =
6240                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6241                    if (pi != null) {
6242                        list.add(pi);
6243                    }
6244                }
6245            }
6246
6247            return new ParceledListSlice<PackageInfo>(list);
6248        }
6249    }
6250
6251    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6252            String[] permissions, boolean[] tmp, int flags, int userId) {
6253        int numMatch = 0;
6254        final PermissionsState permissionsState = ps.getPermissionsState();
6255        for (int i=0; i<permissions.length; i++) {
6256            final String permission = permissions[i];
6257            if (permissionsState.hasPermission(permission, userId)) {
6258                tmp[i] = true;
6259                numMatch++;
6260            } else {
6261                tmp[i] = false;
6262            }
6263        }
6264        if (numMatch == 0) {
6265            return;
6266        }
6267        final PackageInfo pi;
6268        if (ps.pkg != null) {
6269            pi = generatePackageInfo(ps, flags, userId);
6270        } else {
6271            pi = generatePackageInfo(ps, flags, userId);
6272        }
6273        // The above might return null in cases of uninstalled apps or install-state
6274        // skew across users/profiles.
6275        if (pi != null) {
6276            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6277                if (numMatch == permissions.length) {
6278                    pi.requestedPermissions = permissions;
6279                } else {
6280                    pi.requestedPermissions = new String[numMatch];
6281                    numMatch = 0;
6282                    for (int i=0; i<permissions.length; i++) {
6283                        if (tmp[i]) {
6284                            pi.requestedPermissions[numMatch] = permissions[i];
6285                            numMatch++;
6286                        }
6287                    }
6288                }
6289            }
6290            list.add(pi);
6291        }
6292    }
6293
6294    @Override
6295    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6296            String[] permissions, int flags, int userId) {
6297        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6298        flags = updateFlagsForPackage(flags, userId, permissions);
6299        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6300
6301        // writer
6302        synchronized (mPackages) {
6303            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6304            boolean[] tmpBools = new boolean[permissions.length];
6305            if (listUninstalled) {
6306                for (PackageSetting ps : mSettings.mPackages.values()) {
6307                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6308                }
6309            } else {
6310                for (PackageParser.Package pkg : mPackages.values()) {
6311                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6312                    if (ps != null) {
6313                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6314                                userId);
6315                    }
6316                }
6317            }
6318
6319            return new ParceledListSlice<PackageInfo>(list);
6320        }
6321    }
6322
6323    @Override
6324    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6325        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6326        flags = updateFlagsForApplication(flags, userId, null);
6327        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6328
6329        // writer
6330        synchronized (mPackages) {
6331            ArrayList<ApplicationInfo> list;
6332            if (listUninstalled) {
6333                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6334                for (PackageSetting ps : mSettings.mPackages.values()) {
6335                    ApplicationInfo ai;
6336                    if (ps.pkg != null) {
6337                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6338                                ps.readUserState(userId), userId);
6339                    } else {
6340                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6341                    }
6342                    if (ai != null) {
6343                        list.add(ai);
6344                    }
6345                }
6346            } else {
6347                list = new ArrayList<ApplicationInfo>(mPackages.size());
6348                for (PackageParser.Package p : mPackages.values()) {
6349                    if (p.mExtras != null) {
6350                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6351                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6352                        if (ai != null) {
6353                            list.add(ai);
6354                        }
6355                    }
6356                }
6357            }
6358
6359            return new ParceledListSlice<ApplicationInfo>(list);
6360        }
6361    }
6362
6363    @Override
6364    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6365        if (DISABLE_EPHEMERAL_APPS) {
6366            return null;
6367        }
6368
6369        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6370                "getEphemeralApplications");
6371        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6372                true /* requireFullPermission */, false /* checkShell */,
6373                "getEphemeralApplications");
6374        synchronized (mPackages) {
6375            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6376                    .getEphemeralApplicationsLPw(userId);
6377            if (ephemeralApps != null) {
6378                return new ParceledListSlice<>(ephemeralApps);
6379            }
6380        }
6381        return null;
6382    }
6383
6384    @Override
6385    public boolean isEphemeralApplication(String packageName, int userId) {
6386        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6387                true /* requireFullPermission */, false /* checkShell */,
6388                "isEphemeral");
6389        if (DISABLE_EPHEMERAL_APPS) {
6390            return false;
6391        }
6392
6393        if (!isCallerSameApp(packageName)) {
6394            return false;
6395        }
6396        synchronized (mPackages) {
6397            PackageParser.Package pkg = mPackages.get(packageName);
6398            if (pkg != null) {
6399                return pkg.applicationInfo.isEphemeralApp();
6400            }
6401        }
6402        return false;
6403    }
6404
6405    @Override
6406    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6407        if (DISABLE_EPHEMERAL_APPS) {
6408            return null;
6409        }
6410
6411        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6412                true /* requireFullPermission */, false /* checkShell */,
6413                "getCookie");
6414        if (!isCallerSameApp(packageName)) {
6415            return null;
6416        }
6417        synchronized (mPackages) {
6418            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6419                    packageName, userId);
6420        }
6421    }
6422
6423    @Override
6424    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6425        if (DISABLE_EPHEMERAL_APPS) {
6426            return true;
6427        }
6428
6429        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6430                true /* requireFullPermission */, true /* checkShell */,
6431                "setCookie");
6432        if (!isCallerSameApp(packageName)) {
6433            return false;
6434        }
6435        synchronized (mPackages) {
6436            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6437                    packageName, cookie, userId);
6438        }
6439    }
6440
6441    @Override
6442    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6443        if (DISABLE_EPHEMERAL_APPS) {
6444            return null;
6445        }
6446
6447        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6448                "getEphemeralApplicationIcon");
6449        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6450                true /* requireFullPermission */, false /* checkShell */,
6451                "getEphemeralApplicationIcon");
6452        synchronized (mPackages) {
6453            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6454                    packageName, userId);
6455        }
6456    }
6457
6458    private boolean isCallerSameApp(String packageName) {
6459        PackageParser.Package pkg = mPackages.get(packageName);
6460        return pkg != null
6461                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6462    }
6463
6464    @Override
6465    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6466        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6467    }
6468
6469    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6470        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6471
6472        // reader
6473        synchronized (mPackages) {
6474            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6475            final int userId = UserHandle.getCallingUserId();
6476            while (i.hasNext()) {
6477                final PackageParser.Package p = i.next();
6478                if (p.applicationInfo == null) continue;
6479
6480                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6481                        && !p.applicationInfo.isDirectBootAware();
6482                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6483                        && p.applicationInfo.isDirectBootAware();
6484
6485                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6486                        && (!mSafeMode || isSystemApp(p))
6487                        && (matchesUnaware || matchesAware)) {
6488                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6489                    if (ps != null) {
6490                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6491                                ps.readUserState(userId), userId);
6492                        if (ai != null) {
6493                            finalList.add(ai);
6494                        }
6495                    }
6496                }
6497            }
6498        }
6499
6500        return finalList;
6501    }
6502
6503    @Override
6504    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6505        if (!sUserManager.exists(userId)) return null;
6506        flags = updateFlagsForComponent(flags, userId, name);
6507        // reader
6508        synchronized (mPackages) {
6509            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6510            PackageSetting ps = provider != null
6511                    ? mSettings.mPackages.get(provider.owner.packageName)
6512                    : null;
6513            return ps != null
6514                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6515                    ? PackageParser.generateProviderInfo(provider, flags,
6516                            ps.readUserState(userId), userId)
6517                    : null;
6518        }
6519    }
6520
6521    /**
6522     * @deprecated
6523     */
6524    @Deprecated
6525    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6526        // reader
6527        synchronized (mPackages) {
6528            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6529                    .entrySet().iterator();
6530            final int userId = UserHandle.getCallingUserId();
6531            while (i.hasNext()) {
6532                Map.Entry<String, PackageParser.Provider> entry = i.next();
6533                PackageParser.Provider p = entry.getValue();
6534                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6535
6536                if (ps != null && p.syncable
6537                        && (!mSafeMode || (p.info.applicationInfo.flags
6538                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6539                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6540                            ps.readUserState(userId), userId);
6541                    if (info != null) {
6542                        outNames.add(entry.getKey());
6543                        outInfo.add(info);
6544                    }
6545                }
6546            }
6547        }
6548    }
6549
6550    @Override
6551    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6552            int uid, int flags) {
6553        final int userId = processName != null ? UserHandle.getUserId(uid)
6554                : UserHandle.getCallingUserId();
6555        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6556        flags = updateFlagsForComponent(flags, userId, processName);
6557
6558        ArrayList<ProviderInfo> finalList = null;
6559        // reader
6560        synchronized (mPackages) {
6561            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6562            while (i.hasNext()) {
6563                final PackageParser.Provider p = i.next();
6564                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6565                if (ps != null && p.info.authority != null
6566                        && (processName == null
6567                                || (p.info.processName.equals(processName)
6568                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6569                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6570                    if (finalList == null) {
6571                        finalList = new ArrayList<ProviderInfo>(3);
6572                    }
6573                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6574                            ps.readUserState(userId), userId);
6575                    if (info != null) {
6576                        finalList.add(info);
6577                    }
6578                }
6579            }
6580        }
6581
6582        if (finalList != null) {
6583            Collections.sort(finalList, mProviderInitOrderSorter);
6584            return new ParceledListSlice<ProviderInfo>(finalList);
6585        }
6586
6587        return ParceledListSlice.emptyList();
6588    }
6589
6590    @Override
6591    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6592        // reader
6593        synchronized (mPackages) {
6594            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6595            return PackageParser.generateInstrumentationInfo(i, flags);
6596        }
6597    }
6598
6599    @Override
6600    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6601            String targetPackage, int flags) {
6602        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6603    }
6604
6605    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6606            int flags) {
6607        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6608
6609        // reader
6610        synchronized (mPackages) {
6611            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6612            while (i.hasNext()) {
6613                final PackageParser.Instrumentation p = i.next();
6614                if (targetPackage == null
6615                        || targetPackage.equals(p.info.targetPackage)) {
6616                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6617                            flags);
6618                    if (ii != null) {
6619                        finalList.add(ii);
6620                    }
6621                }
6622            }
6623        }
6624
6625        return finalList;
6626    }
6627
6628    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6629        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6630        if (overlays == null) {
6631            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6632            return;
6633        }
6634        for (PackageParser.Package opkg : overlays.values()) {
6635            // Not much to do if idmap fails: we already logged the error
6636            // and we certainly don't want to abort installation of pkg simply
6637            // because an overlay didn't fit properly. For these reasons,
6638            // ignore the return value of createIdmapForPackagePairLI.
6639            createIdmapForPackagePairLI(pkg, opkg);
6640        }
6641    }
6642
6643    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6644            PackageParser.Package opkg) {
6645        if (!opkg.mTrustedOverlay) {
6646            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6647                    opkg.baseCodePath + ": overlay not trusted");
6648            return false;
6649        }
6650        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6651        if (overlaySet == null) {
6652            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6653                    opkg.baseCodePath + " but target package has no known overlays");
6654            return false;
6655        }
6656        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6657        // TODO: generate idmap for split APKs
6658        try {
6659            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6660        } catch (InstallerException e) {
6661            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6662                    + opkg.baseCodePath);
6663            return false;
6664        }
6665        PackageParser.Package[] overlayArray =
6666            overlaySet.values().toArray(new PackageParser.Package[0]);
6667        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6668            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6669                return p1.mOverlayPriority - p2.mOverlayPriority;
6670            }
6671        };
6672        Arrays.sort(overlayArray, cmp);
6673
6674        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6675        int i = 0;
6676        for (PackageParser.Package p : overlayArray) {
6677            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6678        }
6679        return true;
6680    }
6681
6682    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6683        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6684        try {
6685            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6686        } finally {
6687            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6688        }
6689    }
6690
6691    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6692        final File[] files = dir.listFiles();
6693        if (ArrayUtils.isEmpty(files)) {
6694            Log.d(TAG, "No files in app dir " + dir);
6695            return;
6696        }
6697
6698        if (DEBUG_PACKAGE_SCANNING) {
6699            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6700                    + " flags=0x" + Integer.toHexString(parseFlags));
6701        }
6702
6703        for (File file : files) {
6704            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6705                    && !PackageInstallerService.isStageName(file.getName());
6706            if (!isPackage) {
6707                // Ignore entries which are not packages
6708                continue;
6709            }
6710            try {
6711                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6712                        scanFlags, currentTime, null);
6713            } catch (PackageManagerException e) {
6714                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6715
6716                // Delete invalid userdata apps
6717                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6718                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6719                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6720                    removeCodePathLI(file);
6721                }
6722            }
6723        }
6724    }
6725
6726    private static File getSettingsProblemFile() {
6727        File dataDir = Environment.getDataDirectory();
6728        File systemDir = new File(dataDir, "system");
6729        File fname = new File(systemDir, "uiderrors.txt");
6730        return fname;
6731    }
6732
6733    static void reportSettingsProblem(int priority, String msg) {
6734        logCriticalInfo(priority, msg);
6735    }
6736
6737    static void logCriticalInfo(int priority, String msg) {
6738        Slog.println(priority, TAG, msg);
6739        EventLogTags.writePmCriticalInfo(msg);
6740        try {
6741            File fname = getSettingsProblemFile();
6742            FileOutputStream out = new FileOutputStream(fname, true);
6743            PrintWriter pw = new FastPrintWriter(out);
6744            SimpleDateFormat formatter = new SimpleDateFormat();
6745            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6746            pw.println(dateString + ": " + msg);
6747            pw.close();
6748            FileUtils.setPermissions(
6749                    fname.toString(),
6750                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6751                    -1, -1);
6752        } catch (java.io.IOException e) {
6753        }
6754    }
6755
6756    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6757            final int policyFlags) throws PackageManagerException {
6758        if (ps != null
6759                && ps.codePath.equals(srcFile)
6760                && ps.timeStamp == srcFile.lastModified()
6761                && !isCompatSignatureUpdateNeeded(pkg)
6762                && !isRecoverSignatureUpdateNeeded(pkg)) {
6763            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6764            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6765            ArraySet<PublicKey> signingKs;
6766            synchronized (mPackages) {
6767                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6768            }
6769            if (ps.signatures.mSignatures != null
6770                    && ps.signatures.mSignatures.length != 0
6771                    && signingKs != null) {
6772                // Optimization: reuse the existing cached certificates
6773                // if the package appears to be unchanged.
6774                pkg.mSignatures = ps.signatures.mSignatures;
6775                pkg.mSigningKeys = signingKs;
6776                return;
6777            }
6778
6779            Slog.w(TAG, "PackageSetting for " + ps.name
6780                    + " is missing signatures.  Collecting certs again to recover them.");
6781        } else {
6782            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6783        }
6784
6785        try {
6786            PackageParser.collectCertificates(pkg, policyFlags);
6787        } catch (PackageParserException e) {
6788            throw PackageManagerException.from(e);
6789        }
6790    }
6791
6792    /**
6793     *  Traces a package scan.
6794     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6795     */
6796    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6797            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6798        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6799        try {
6800            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6801        } finally {
6802            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6803        }
6804    }
6805
6806    /**
6807     *  Scans a package and returns the newly parsed package.
6808     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6809     */
6810    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6811            long currentTime, UserHandle user) throws PackageManagerException {
6812        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6813        PackageParser pp = new PackageParser();
6814        pp.setSeparateProcesses(mSeparateProcesses);
6815        pp.setOnlyCoreApps(mOnlyCore);
6816        pp.setDisplayMetrics(mMetrics);
6817
6818        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6819            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6820        }
6821
6822        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6823        final PackageParser.Package pkg;
6824        try {
6825            pkg = pp.parsePackage(scanFile, parseFlags);
6826        } catch (PackageParserException e) {
6827            throw PackageManagerException.from(e);
6828        } finally {
6829            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6830        }
6831
6832        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6833    }
6834
6835    /**
6836     *  Scans a package and returns the newly parsed package.
6837     *  @throws PackageManagerException on a parse error.
6838     */
6839    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6840            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6841            throws PackageManagerException {
6842        // If the package has children and this is the first dive in the function
6843        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6844        // packages (parent and children) would be successfully scanned before the
6845        // actual scan since scanning mutates internal state and we want to atomically
6846        // install the package and its children.
6847        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6848            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6849                scanFlags |= SCAN_CHECK_ONLY;
6850            }
6851        } else {
6852            scanFlags &= ~SCAN_CHECK_ONLY;
6853        }
6854
6855        // Scan the parent
6856        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6857                scanFlags, currentTime, user);
6858
6859        // Scan the children
6860        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6861        for (int i = 0; i < childCount; i++) {
6862            PackageParser.Package childPackage = pkg.childPackages.get(i);
6863            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6864                    currentTime, user);
6865        }
6866
6867
6868        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6869            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6870        }
6871
6872        return scannedPkg;
6873    }
6874
6875    /**
6876     *  Scans a package and returns the newly parsed package.
6877     *  @throws PackageManagerException on a parse error.
6878     */
6879    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6880            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6881            throws PackageManagerException {
6882        PackageSetting ps = null;
6883        PackageSetting updatedPkg;
6884        // reader
6885        synchronized (mPackages) {
6886            // Look to see if we already know about this package.
6887            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6888            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6889                // This package has been renamed to its original name.  Let's
6890                // use that.
6891                ps = mSettings.peekPackageLPr(oldName);
6892            }
6893            // If there was no original package, see one for the real package name.
6894            if (ps == null) {
6895                ps = mSettings.peekPackageLPr(pkg.packageName);
6896            }
6897            // Check to see if this package could be hiding/updating a system
6898            // package.  Must look for it either under the original or real
6899            // package name depending on our state.
6900            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6901            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6902
6903            // If this is a package we don't know about on the system partition, we
6904            // may need to remove disabled child packages on the system partition
6905            // or may need to not add child packages if the parent apk is updated
6906            // on the data partition and no longer defines this child package.
6907            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6908                // If this is a parent package for an updated system app and this system
6909                // app got an OTA update which no longer defines some of the child packages
6910                // we have to prune them from the disabled system packages.
6911                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6912                if (disabledPs != null) {
6913                    final int scannedChildCount = (pkg.childPackages != null)
6914                            ? pkg.childPackages.size() : 0;
6915                    final int disabledChildCount = disabledPs.childPackageNames != null
6916                            ? disabledPs.childPackageNames.size() : 0;
6917                    for (int i = 0; i < disabledChildCount; i++) {
6918                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6919                        boolean disabledPackageAvailable = false;
6920                        for (int j = 0; j < scannedChildCount; j++) {
6921                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6922                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6923                                disabledPackageAvailable = true;
6924                                break;
6925                            }
6926                         }
6927                         if (!disabledPackageAvailable) {
6928                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6929                         }
6930                    }
6931                }
6932            }
6933        }
6934
6935        boolean updatedPkgBetter = false;
6936        // First check if this is a system package that may involve an update
6937        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6938            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6939            // it needs to drop FLAG_PRIVILEGED.
6940            if (locationIsPrivileged(scanFile)) {
6941                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6942            } else {
6943                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6944            }
6945
6946            if (ps != null && !ps.codePath.equals(scanFile)) {
6947                // The path has changed from what was last scanned...  check the
6948                // version of the new path against what we have stored to determine
6949                // what to do.
6950                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6951                if (pkg.mVersionCode <= ps.versionCode) {
6952                    // The system package has been updated and the code path does not match
6953                    // Ignore entry. Skip it.
6954                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6955                            + " ignored: updated version " + ps.versionCode
6956                            + " better than this " + pkg.mVersionCode);
6957                    if (!updatedPkg.codePath.equals(scanFile)) {
6958                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6959                                + ps.name + " changing from " + updatedPkg.codePathString
6960                                + " to " + scanFile);
6961                        updatedPkg.codePath = scanFile;
6962                        updatedPkg.codePathString = scanFile.toString();
6963                        updatedPkg.resourcePath = scanFile;
6964                        updatedPkg.resourcePathString = scanFile.toString();
6965                    }
6966                    updatedPkg.pkg = pkg;
6967                    updatedPkg.versionCode = pkg.mVersionCode;
6968
6969                    // Update the disabled system child packages to point to the package too.
6970                    final int childCount = updatedPkg.childPackageNames != null
6971                            ? updatedPkg.childPackageNames.size() : 0;
6972                    for (int i = 0; i < childCount; i++) {
6973                        String childPackageName = updatedPkg.childPackageNames.get(i);
6974                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6975                                childPackageName);
6976                        if (updatedChildPkg != null) {
6977                            updatedChildPkg.pkg = pkg;
6978                            updatedChildPkg.versionCode = pkg.mVersionCode;
6979                        }
6980                    }
6981
6982                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6983                            + scanFile + " ignored: updated version " + ps.versionCode
6984                            + " better than this " + pkg.mVersionCode);
6985                } else {
6986                    // The current app on the system partition is better than
6987                    // what we have updated to on the data partition; switch
6988                    // back to the system partition version.
6989                    // At this point, its safely assumed that package installation for
6990                    // apps in system partition will go through. If not there won't be a working
6991                    // version of the app
6992                    // writer
6993                    synchronized (mPackages) {
6994                        // Just remove the loaded entries from package lists.
6995                        mPackages.remove(ps.name);
6996                    }
6997
6998                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6999                            + " reverting from " + ps.codePathString
7000                            + ": new version " + pkg.mVersionCode
7001                            + " better than installed " + ps.versionCode);
7002
7003                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7004                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7005                    synchronized (mInstallLock) {
7006                        args.cleanUpResourcesLI();
7007                    }
7008                    synchronized (mPackages) {
7009                        mSettings.enableSystemPackageLPw(ps.name);
7010                    }
7011                    updatedPkgBetter = true;
7012                }
7013            }
7014        }
7015
7016        if (updatedPkg != null) {
7017            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7018            // initially
7019            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7020
7021            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7022            // flag set initially
7023            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7024                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7025            }
7026        }
7027
7028        // Verify certificates against what was last scanned
7029        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7030
7031        /*
7032         * A new system app appeared, but we already had a non-system one of the
7033         * same name installed earlier.
7034         */
7035        boolean shouldHideSystemApp = false;
7036        if (updatedPkg == null && ps != null
7037                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7038            /*
7039             * Check to make sure the signatures match first. If they don't,
7040             * wipe the installed application and its data.
7041             */
7042            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7043                    != PackageManager.SIGNATURE_MATCH) {
7044                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7045                        + " signatures don't match existing userdata copy; removing");
7046                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7047                        "scanPackageInternalLI")) {
7048                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7049                }
7050                ps = null;
7051            } else {
7052                /*
7053                 * If the newly-added system app is an older version than the
7054                 * already installed version, hide it. It will be scanned later
7055                 * and re-added like an update.
7056                 */
7057                if (pkg.mVersionCode <= ps.versionCode) {
7058                    shouldHideSystemApp = true;
7059                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7060                            + " but new version " + pkg.mVersionCode + " better than installed "
7061                            + ps.versionCode + "; hiding system");
7062                } else {
7063                    /*
7064                     * The newly found system app is a newer version that the
7065                     * one previously installed. Simply remove the
7066                     * already-installed application and replace it with our own
7067                     * while keeping the application data.
7068                     */
7069                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7070                            + " reverting from " + ps.codePathString + ": new version "
7071                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7072                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7073                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7074                    synchronized (mInstallLock) {
7075                        args.cleanUpResourcesLI();
7076                    }
7077                }
7078            }
7079        }
7080
7081        // The apk is forward locked (not public) if its code and resources
7082        // are kept in different files. (except for app in either system or
7083        // vendor path).
7084        // TODO grab this value from PackageSettings
7085        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7086            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7087                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7088            }
7089        }
7090
7091        // TODO: extend to support forward-locked splits
7092        String resourcePath = null;
7093        String baseResourcePath = null;
7094        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7095            if (ps != null && ps.resourcePathString != null) {
7096                resourcePath = ps.resourcePathString;
7097                baseResourcePath = ps.resourcePathString;
7098            } else {
7099                // Should not happen at all. Just log an error.
7100                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7101            }
7102        } else {
7103            resourcePath = pkg.codePath;
7104            baseResourcePath = pkg.baseCodePath;
7105        }
7106
7107        // Set application objects path explicitly.
7108        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7109        pkg.setApplicationInfoCodePath(pkg.codePath);
7110        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7111        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7112        pkg.setApplicationInfoResourcePath(resourcePath);
7113        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7114        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7115
7116        // Note that we invoke the following method only if we are about to unpack an application
7117        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7118                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7119
7120        /*
7121         * If the system app should be overridden by a previously installed
7122         * data, hide the system app now and let the /data/app scan pick it up
7123         * again.
7124         */
7125        if (shouldHideSystemApp) {
7126            synchronized (mPackages) {
7127                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7128            }
7129        }
7130
7131        return scannedPkg;
7132    }
7133
7134    private static String fixProcessName(String defProcessName,
7135            String processName, int uid) {
7136        if (processName == null) {
7137            return defProcessName;
7138        }
7139        return processName;
7140    }
7141
7142    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7143            throws PackageManagerException {
7144        if (pkgSetting.signatures.mSignatures != null) {
7145            // Already existing package. Make sure signatures match
7146            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7147                    == PackageManager.SIGNATURE_MATCH;
7148            if (!match) {
7149                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7150                        == PackageManager.SIGNATURE_MATCH;
7151            }
7152            if (!match) {
7153                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7154                        == PackageManager.SIGNATURE_MATCH;
7155            }
7156            if (!match) {
7157                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7158                        + pkg.packageName + " signatures do not match the "
7159                        + "previously installed version; ignoring!");
7160            }
7161        }
7162
7163        // Check for shared user signatures
7164        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7165            // Already existing package. Make sure signatures match
7166            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7167                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7168            if (!match) {
7169                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7170                        == PackageManager.SIGNATURE_MATCH;
7171            }
7172            if (!match) {
7173                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7174                        == PackageManager.SIGNATURE_MATCH;
7175            }
7176            if (!match) {
7177                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7178                        "Package " + pkg.packageName
7179                        + " has no signatures that match those in shared user "
7180                        + pkgSetting.sharedUser.name + "; ignoring!");
7181            }
7182        }
7183    }
7184
7185    /**
7186     * Enforces that only the system UID or root's UID can call a method exposed
7187     * via Binder.
7188     *
7189     * @param message used as message if SecurityException is thrown
7190     * @throws SecurityException if the caller is not system or root
7191     */
7192    private static final void enforceSystemOrRoot(String message) {
7193        final int uid = Binder.getCallingUid();
7194        if (uid != Process.SYSTEM_UID && uid != 0) {
7195            throw new SecurityException(message);
7196        }
7197    }
7198
7199    @Override
7200    public void performFstrimIfNeeded() {
7201        enforceSystemOrRoot("Only the system can request fstrim");
7202
7203        // Before everything else, see whether we need to fstrim.
7204        try {
7205            IMountService ms = PackageHelper.getMountService();
7206            if (ms != null) {
7207                final boolean isUpgrade = isUpgrade();
7208                boolean doTrim = isUpgrade;
7209                if (doTrim) {
7210                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7211                } else {
7212                    final long interval = android.provider.Settings.Global.getLong(
7213                            mContext.getContentResolver(),
7214                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7215                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7216                    if (interval > 0) {
7217                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7218                        if (timeSinceLast > interval) {
7219                            doTrim = true;
7220                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7221                                    + "; running immediately");
7222                        }
7223                    }
7224                }
7225                if (doTrim) {
7226                    if (!isFirstBoot()) {
7227                        try {
7228                            ActivityManagerNative.getDefault().showBootMessage(
7229                                    mContext.getResources().getString(
7230                                            R.string.android_upgrading_fstrim), true);
7231                        } catch (RemoteException e) {
7232                        }
7233                    }
7234                    ms.runMaintenance();
7235                }
7236            } else {
7237                Slog.e(TAG, "Mount service unavailable!");
7238            }
7239        } catch (RemoteException e) {
7240            // Can't happen; MountService is local
7241        }
7242    }
7243
7244    @Override
7245    public void updatePackagesIfNeeded() {
7246        enforceSystemOrRoot("Only the system can request package update");
7247
7248        // We need to re-extract after an OTA.
7249        boolean causeUpgrade = isUpgrade();
7250
7251        // First boot or factory reset.
7252        // Note: we also handle devices that are upgrading to N right now as if it is their
7253        //       first boot, as they do not have profile data.
7254        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7255
7256        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7257        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7258
7259        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7260            return;
7261        }
7262
7263        List<PackageParser.Package> pkgs;
7264        synchronized (mPackages) {
7265            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7266        }
7267
7268        final long startTime = System.nanoTime();
7269        final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */,
7270                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7271
7272        final int elapsedTimeSeconds =
7273                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7274
7275        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7276        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7277        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7278        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7279        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7280    }
7281
7282    /**
7283     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7284     * containing statistics about the invocation. The array consists of three elements,
7285     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7286     * and {@code numberOfPackagesFailed}.
7287     */
7288    private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog,
7289            String compilerFilter) {
7290
7291        int numberOfPackagesVisited = 0;
7292        int numberOfPackagesOptimized = 0;
7293        int numberOfPackagesSkipped = 0;
7294        int numberOfPackagesFailed = 0;
7295        final int numberOfPackagesToDexopt = pkgs.size();
7296
7297        for (PackageParser.Package pkg : pkgs) {
7298            numberOfPackagesVisited++;
7299
7300            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7301                if (DEBUG_DEXOPT) {
7302                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7303                }
7304                numberOfPackagesSkipped++;
7305                continue;
7306            }
7307
7308            if (DEBUG_DEXOPT) {
7309                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7310                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7311            }
7312
7313            if (showDialog) {
7314                try {
7315                    ActivityManagerNative.getDefault().showBootMessage(
7316                            mContext.getResources().getString(R.string.android_upgrading_apk,
7317                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7318                } catch (RemoteException e) {
7319                }
7320            }
7321
7322            // checkProfiles is false to avoid merging profiles during boot which
7323            // might interfere with background compilation (b/28612421).
7324            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7325            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7326            // trade-off worth doing to save boot time work.
7327            int dexOptStatus = performDexOptTraced(pkg.packageName,
7328                    false /* checkProfiles */,
7329                    compilerFilter,
7330                    false /* force */);
7331            switch (dexOptStatus) {
7332                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7333                    numberOfPackagesOptimized++;
7334                    break;
7335                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7336                    numberOfPackagesSkipped++;
7337                    break;
7338                case PackageDexOptimizer.DEX_OPT_FAILED:
7339                    numberOfPackagesFailed++;
7340                    break;
7341                default:
7342                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7343                    break;
7344            }
7345        }
7346
7347        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7348                numberOfPackagesFailed };
7349    }
7350
7351    @Override
7352    public void notifyPackageUse(String packageName, int reason) {
7353        synchronized (mPackages) {
7354            PackageParser.Package p = mPackages.get(packageName);
7355            if (p == null) {
7356                return;
7357            }
7358            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7359        }
7360    }
7361
7362    // TODO: this is not used nor needed. Delete it.
7363    @Override
7364    public boolean performDexOptIfNeeded(String packageName) {
7365        int dexOptStatus = performDexOptTraced(packageName,
7366                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7367        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7368    }
7369
7370    @Override
7371    public boolean performDexOpt(String packageName,
7372            boolean checkProfiles, int compileReason, boolean force) {
7373        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7374                getCompilerFilterForReason(compileReason), force);
7375        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7376    }
7377
7378    @Override
7379    public boolean performDexOptMode(String packageName,
7380            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7381        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7382                targetCompilerFilter, force);
7383        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7384    }
7385
7386    private int performDexOptTraced(String packageName,
7387                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7388        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7389        try {
7390            return performDexOptInternal(packageName, checkProfiles,
7391                    targetCompilerFilter, force);
7392        } finally {
7393            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7394        }
7395    }
7396
7397    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7398    // if the package can now be considered up to date for the given filter.
7399    private int performDexOptInternal(String packageName,
7400                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7401        PackageParser.Package p;
7402        synchronized (mPackages) {
7403            p = mPackages.get(packageName);
7404            if (p == null) {
7405                // Package could not be found. Report failure.
7406                return PackageDexOptimizer.DEX_OPT_FAILED;
7407            }
7408            mPackageUsage.write(false);
7409        }
7410        long callingId = Binder.clearCallingIdentity();
7411        try {
7412            synchronized (mInstallLock) {
7413                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7414                        targetCompilerFilter, force);
7415            }
7416        } finally {
7417            Binder.restoreCallingIdentity(callingId);
7418        }
7419    }
7420
7421    public ArraySet<String> getOptimizablePackages() {
7422        ArraySet<String> pkgs = new ArraySet<String>();
7423        synchronized (mPackages) {
7424            for (PackageParser.Package p : mPackages.values()) {
7425                if (PackageDexOptimizer.canOptimizePackage(p)) {
7426                    pkgs.add(p.packageName);
7427                }
7428            }
7429        }
7430        return pkgs;
7431    }
7432
7433    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7434            boolean checkProfiles, String targetCompilerFilter,
7435            boolean force) {
7436        // Select the dex optimizer based on the force parameter.
7437        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7438        //       allocate an object here.
7439        PackageDexOptimizer pdo = force
7440                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7441                : mPackageDexOptimizer;
7442
7443        // Optimize all dependencies first. Note: we ignore the return value and march on
7444        // on errors.
7445        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7446        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7447        if (!deps.isEmpty()) {
7448            for (PackageParser.Package depPackage : deps) {
7449                // TODO: Analyze and investigate if we (should) profile libraries.
7450                // Currently this will do a full compilation of the library by default.
7451                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7452                        false /* checkProfiles */,
7453                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7454            }
7455        }
7456        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7457                targetCompilerFilter);
7458    }
7459
7460    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7461        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7462            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7463            Set<String> collectedNames = new HashSet<>();
7464            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7465
7466            retValue.remove(p);
7467
7468            return retValue;
7469        } else {
7470            return Collections.emptyList();
7471        }
7472    }
7473
7474    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7475            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7476        if (!collectedNames.contains(p.packageName)) {
7477            collectedNames.add(p.packageName);
7478            collected.add(p);
7479
7480            if (p.usesLibraries != null) {
7481                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7482            }
7483            if (p.usesOptionalLibraries != null) {
7484                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7485                        collectedNames);
7486            }
7487        }
7488    }
7489
7490    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7491            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7492        for (String libName : libs) {
7493            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7494            if (libPkg != null) {
7495                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7496            }
7497        }
7498    }
7499
7500    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7501        synchronized (mPackages) {
7502            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7503            if (lib != null && lib.apk != null) {
7504                return mPackages.get(lib.apk);
7505            }
7506        }
7507        return null;
7508    }
7509
7510    public void shutdown() {
7511        mPackageUsage.write(true);
7512    }
7513
7514    @Override
7515    public void dumpProfiles(String packageName) {
7516        PackageParser.Package pkg;
7517        synchronized (mPackages) {
7518            pkg = mPackages.get(packageName);
7519            if (pkg == null) {
7520                throw new IllegalArgumentException("Unknown package: " + packageName);
7521            }
7522        }
7523        /* Only the shell or the app user should be able to dump profiles. */
7524        int callingUid = Binder.getCallingUid();
7525        if (callingUid != Process.SHELL_UID && callingUid != pkg.applicationInfo.uid) {
7526            throw new SecurityException("dumpProfiles");
7527        }
7528
7529        synchronized (mInstallLock) {
7530            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7531            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7532            try {
7533                final File codeFile = new File(pkg.applicationInfo.getCodePath());
7534                List<String> allCodePaths = Collections.EMPTY_LIST;
7535                if (codeFile != null && codeFile.exists()) {
7536                    try {
7537                        final PackageLite codePkg = PackageParser.parsePackageLite(codeFile, 0);
7538                        allCodePaths = codePkg.getAllCodePaths();
7539                    } catch (PackageParserException e) {
7540                        // Well, we tried.
7541                    }
7542                }
7543                String gid = Integer.toString(sharedGid);
7544                String codePaths = TextUtils.join(";", allCodePaths);
7545                mInstaller.dumpProfiles(gid, packageName, codePaths);
7546            } catch (InstallerException e) {
7547                Slog.w(TAG, "Failed to dump profiles", e);
7548            }
7549            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7550        }
7551    }
7552
7553    @Override
7554    public void forceDexOpt(String packageName) {
7555        enforceSystemOrRoot("forceDexOpt");
7556
7557        PackageParser.Package pkg;
7558        synchronized (mPackages) {
7559            pkg = mPackages.get(packageName);
7560            if (pkg == null) {
7561                throw new IllegalArgumentException("Unknown package: " + packageName);
7562            }
7563        }
7564
7565        synchronized (mInstallLock) {
7566            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7567
7568            // Whoever is calling forceDexOpt wants a fully compiled package.
7569            // Don't use profiles since that may cause compilation to be skipped.
7570            final int res = performDexOptInternalWithDependenciesLI(pkg,
7571                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7572                    true /* force */);
7573
7574            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7575            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7576                throw new IllegalStateException("Failed to dexopt: " + res);
7577            }
7578        }
7579    }
7580
7581    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7582        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7583            Slog.w(TAG, "Unable to update from " + oldPkg.name
7584                    + " to " + newPkg.packageName
7585                    + ": old package not in system partition");
7586            return false;
7587        } else if (mPackages.get(oldPkg.name) != null) {
7588            Slog.w(TAG, "Unable to update from " + oldPkg.name
7589                    + " to " + newPkg.packageName
7590                    + ": old package still exists");
7591            return false;
7592        }
7593        return true;
7594    }
7595
7596    void removeCodePathLI(File codePath) {
7597        if (codePath.isDirectory()) {
7598            try {
7599                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7600            } catch (InstallerException e) {
7601                Slog.w(TAG, "Failed to remove code path", e);
7602            }
7603        } else {
7604            codePath.delete();
7605        }
7606    }
7607
7608    private int[] resolveUserIds(int userId) {
7609        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7610    }
7611
7612    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7613        if (pkg == null) {
7614            Slog.wtf(TAG, "Package was null!", new Throwable());
7615            return;
7616        }
7617        clearAppDataLeafLIF(pkg, userId, flags);
7618        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7619        for (int i = 0; i < childCount; i++) {
7620            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7621        }
7622    }
7623
7624    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7625        final PackageSetting ps;
7626        synchronized (mPackages) {
7627            ps = mSettings.mPackages.get(pkg.packageName);
7628        }
7629        for (int realUserId : resolveUserIds(userId)) {
7630            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7631            try {
7632                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7633                        ceDataInode);
7634            } catch (InstallerException e) {
7635                Slog.w(TAG, String.valueOf(e));
7636            }
7637        }
7638    }
7639
7640    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7641        if (pkg == null) {
7642            Slog.wtf(TAG, "Package was null!", new Throwable());
7643            return;
7644        }
7645        destroyAppDataLeafLIF(pkg, userId, flags);
7646        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7647        for (int i = 0; i < childCount; i++) {
7648            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7649        }
7650    }
7651
7652    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7653        final PackageSetting ps;
7654        synchronized (mPackages) {
7655            ps = mSettings.mPackages.get(pkg.packageName);
7656        }
7657        for (int realUserId : resolveUserIds(userId)) {
7658            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7659            try {
7660                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7661                        ceDataInode);
7662            } catch (InstallerException e) {
7663                Slog.w(TAG, String.valueOf(e));
7664            }
7665        }
7666    }
7667
7668    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7669        if (pkg == null) {
7670            Slog.wtf(TAG, "Package was null!", new Throwable());
7671            return;
7672        }
7673        destroyAppProfilesLeafLIF(pkg);
7674        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7675        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7676        for (int i = 0; i < childCount; i++) {
7677            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7678            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7679                    true /* removeBaseMarker */);
7680        }
7681    }
7682
7683    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7684            boolean removeBaseMarker) {
7685        if (pkg.isForwardLocked()) {
7686            return;
7687        }
7688
7689        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7690            try {
7691                path = PackageManagerServiceUtils.realpath(new File(path));
7692            } catch (IOException e) {
7693                // TODO: Should we return early here ?
7694                Slog.w(TAG, "Failed to get canonical path", e);
7695                continue;
7696            }
7697
7698            final String useMarker = path.replace('/', '@');
7699            for (int realUserId : resolveUserIds(userId)) {
7700                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7701                if (removeBaseMarker) {
7702                    File foreignUseMark = new File(profileDir, useMarker);
7703                    if (foreignUseMark.exists()) {
7704                        if (!foreignUseMark.delete()) {
7705                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7706                                    + pkg.packageName);
7707                        }
7708                    }
7709                }
7710
7711                File[] markers = profileDir.listFiles();
7712                if (markers != null) {
7713                    final String searchString = "@" + pkg.packageName + "@";
7714                    // We also delete all markers that contain the package name we're
7715                    // uninstalling. These are associated with secondary dex-files belonging
7716                    // to the package. Reconstructing the path of these dex files is messy
7717                    // in general.
7718                    for (File marker : markers) {
7719                        if (marker.getName().indexOf(searchString) > 0) {
7720                            if (!marker.delete()) {
7721                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7722                                    + pkg.packageName);
7723                            }
7724                        }
7725                    }
7726                }
7727            }
7728        }
7729    }
7730
7731    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7732        try {
7733            mInstaller.destroyAppProfiles(pkg.packageName);
7734        } catch (InstallerException e) {
7735            Slog.w(TAG, String.valueOf(e));
7736        }
7737    }
7738
7739    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7740        if (pkg == null) {
7741            Slog.wtf(TAG, "Package was null!", new Throwable());
7742            return;
7743        }
7744        clearAppProfilesLeafLIF(pkg);
7745        // We don't remove the base foreign use marker when clearing profiles because
7746        // we will rename it when the app is updated. Unlike the actual profile contents,
7747        // the foreign use marker is good across installs.
7748        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7749        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7750        for (int i = 0; i < childCount; i++) {
7751            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7752        }
7753    }
7754
7755    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7756        try {
7757            mInstaller.clearAppProfiles(pkg.packageName);
7758        } catch (InstallerException e) {
7759            Slog.w(TAG, String.valueOf(e));
7760        }
7761    }
7762
7763    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7764            long lastUpdateTime) {
7765        // Set parent install/update time
7766        PackageSetting ps = (PackageSetting) pkg.mExtras;
7767        if (ps != null) {
7768            ps.firstInstallTime = firstInstallTime;
7769            ps.lastUpdateTime = lastUpdateTime;
7770        }
7771        // Set children install/update time
7772        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7773        for (int i = 0; i < childCount; i++) {
7774            PackageParser.Package childPkg = pkg.childPackages.get(i);
7775            ps = (PackageSetting) childPkg.mExtras;
7776            if (ps != null) {
7777                ps.firstInstallTime = firstInstallTime;
7778                ps.lastUpdateTime = lastUpdateTime;
7779            }
7780        }
7781    }
7782
7783    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7784            PackageParser.Package changingLib) {
7785        if (file.path != null) {
7786            usesLibraryFiles.add(file.path);
7787            return;
7788        }
7789        PackageParser.Package p = mPackages.get(file.apk);
7790        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7791            // If we are doing this while in the middle of updating a library apk,
7792            // then we need to make sure to use that new apk for determining the
7793            // dependencies here.  (We haven't yet finished committing the new apk
7794            // to the package manager state.)
7795            if (p == null || p.packageName.equals(changingLib.packageName)) {
7796                p = changingLib;
7797            }
7798        }
7799        if (p != null) {
7800            usesLibraryFiles.addAll(p.getAllCodePaths());
7801        }
7802    }
7803
7804    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7805            PackageParser.Package changingLib) throws PackageManagerException {
7806        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7807            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7808            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7809            for (int i=0; i<N; i++) {
7810                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7811                if (file == null) {
7812                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7813                            "Package " + pkg.packageName + " requires unavailable shared library "
7814                            + pkg.usesLibraries.get(i) + "; failing!");
7815                }
7816                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7817            }
7818            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7819            for (int i=0; i<N; i++) {
7820                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7821                if (file == null) {
7822                    Slog.w(TAG, "Package " + pkg.packageName
7823                            + " desires unavailable shared library "
7824                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7825                } else {
7826                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7827                }
7828            }
7829            N = usesLibraryFiles.size();
7830            if (N > 0) {
7831                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7832            } else {
7833                pkg.usesLibraryFiles = null;
7834            }
7835        }
7836    }
7837
7838    private static boolean hasString(List<String> list, List<String> which) {
7839        if (list == null) {
7840            return false;
7841        }
7842        for (int i=list.size()-1; i>=0; i--) {
7843            for (int j=which.size()-1; j>=0; j--) {
7844                if (which.get(j).equals(list.get(i))) {
7845                    return true;
7846                }
7847            }
7848        }
7849        return false;
7850    }
7851
7852    private void updateAllSharedLibrariesLPw() {
7853        for (PackageParser.Package pkg : mPackages.values()) {
7854            try {
7855                updateSharedLibrariesLPw(pkg, null);
7856            } catch (PackageManagerException e) {
7857                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7858            }
7859        }
7860    }
7861
7862    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7863            PackageParser.Package changingPkg) {
7864        ArrayList<PackageParser.Package> res = null;
7865        for (PackageParser.Package pkg : mPackages.values()) {
7866            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7867                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7868                if (res == null) {
7869                    res = new ArrayList<PackageParser.Package>();
7870                }
7871                res.add(pkg);
7872                try {
7873                    updateSharedLibrariesLPw(pkg, changingPkg);
7874                } catch (PackageManagerException e) {
7875                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7876                }
7877            }
7878        }
7879        return res;
7880    }
7881
7882    /**
7883     * Derive the value of the {@code cpuAbiOverride} based on the provided
7884     * value and an optional stored value from the package settings.
7885     */
7886    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7887        String cpuAbiOverride = null;
7888
7889        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7890            cpuAbiOverride = null;
7891        } else if (abiOverride != null) {
7892            cpuAbiOverride = abiOverride;
7893        } else if (settings != null) {
7894            cpuAbiOverride = settings.cpuAbiOverrideString;
7895        }
7896
7897        return cpuAbiOverride;
7898    }
7899
7900    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7901            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7902                    throws PackageManagerException {
7903        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7904        // If the package has children and this is the first dive in the function
7905        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7906        // whether all packages (parent and children) would be successfully scanned
7907        // before the actual scan since scanning mutates internal state and we want
7908        // to atomically install the package and its children.
7909        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7910            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7911                scanFlags |= SCAN_CHECK_ONLY;
7912            }
7913        } else {
7914            scanFlags &= ~SCAN_CHECK_ONLY;
7915        }
7916
7917        final PackageParser.Package scannedPkg;
7918        try {
7919            // Scan the parent
7920            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7921            // Scan the children
7922            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7923            for (int i = 0; i < childCount; i++) {
7924                PackageParser.Package childPkg = pkg.childPackages.get(i);
7925                scanPackageLI(childPkg, policyFlags,
7926                        scanFlags, currentTime, user);
7927            }
7928        } finally {
7929            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7930        }
7931
7932        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7933            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7934        }
7935
7936        return scannedPkg;
7937    }
7938
7939    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7940            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7941        boolean success = false;
7942        try {
7943            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7944                    currentTime, user);
7945            success = true;
7946            return res;
7947        } finally {
7948            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7949                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7950                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7951                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7952                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7953            }
7954        }
7955    }
7956
7957    /**
7958     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7959     */
7960    private static boolean apkHasCode(String fileName) {
7961        StrictJarFile jarFile = null;
7962        try {
7963            jarFile = new StrictJarFile(fileName,
7964                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7965            return jarFile.findEntry("classes.dex") != null;
7966        } catch (IOException ignore) {
7967        } finally {
7968            try {
7969                jarFile.close();
7970            } catch (IOException ignore) {}
7971        }
7972        return false;
7973    }
7974
7975    /**
7976     * Enforces code policy for the package. This ensures that if an APK has
7977     * declared hasCode="true" in its manifest that the APK actually contains
7978     * code.
7979     *
7980     * @throws PackageManagerException If bytecode could not be found when it should exist
7981     */
7982    private static void enforceCodePolicy(PackageParser.Package pkg)
7983            throws PackageManagerException {
7984        final boolean shouldHaveCode =
7985                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7986        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7987            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7988                    "Package " + pkg.baseCodePath + " code is missing");
7989        }
7990
7991        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7992            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7993                final boolean splitShouldHaveCode =
7994                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7995                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7996                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7997                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7998                }
7999            }
8000        }
8001    }
8002
8003    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8004            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8005            throws PackageManagerException {
8006        final File scanFile = new File(pkg.codePath);
8007        if (pkg.applicationInfo.getCodePath() == null ||
8008                pkg.applicationInfo.getResourcePath() == null) {
8009            // Bail out. The resource and code paths haven't been set.
8010            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8011                    "Code and resource paths haven't been set correctly");
8012        }
8013
8014        // Apply policy
8015        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8016            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8017            if (pkg.applicationInfo.isDirectBootAware()) {
8018                // we're direct boot aware; set for all components
8019                for (PackageParser.Service s : pkg.services) {
8020                    s.info.encryptionAware = s.info.directBootAware = true;
8021                }
8022                for (PackageParser.Provider p : pkg.providers) {
8023                    p.info.encryptionAware = p.info.directBootAware = true;
8024                }
8025                for (PackageParser.Activity a : pkg.activities) {
8026                    a.info.encryptionAware = a.info.directBootAware = true;
8027                }
8028                for (PackageParser.Activity r : pkg.receivers) {
8029                    r.info.encryptionAware = r.info.directBootAware = true;
8030                }
8031            }
8032        } else {
8033            // Only allow system apps to be flagged as core apps.
8034            pkg.coreApp = false;
8035            // clear flags not applicable to regular apps
8036            pkg.applicationInfo.privateFlags &=
8037                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8038            pkg.applicationInfo.privateFlags &=
8039                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8040        }
8041        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8042
8043        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8044            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8045        }
8046
8047        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8048            enforceCodePolicy(pkg);
8049        }
8050
8051        if (mCustomResolverComponentName != null &&
8052                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8053            setUpCustomResolverActivity(pkg);
8054        }
8055
8056        if (pkg.packageName.equals("android")) {
8057            synchronized (mPackages) {
8058                if (mAndroidApplication != null) {
8059                    Slog.w(TAG, "*************************************************");
8060                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8061                    Slog.w(TAG, " file=" + scanFile);
8062                    Slog.w(TAG, "*************************************************");
8063                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8064                            "Core android package being redefined.  Skipping.");
8065                }
8066
8067                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8068                    // Set up information for our fall-back user intent resolution activity.
8069                    mPlatformPackage = pkg;
8070                    pkg.mVersionCode = mSdkVersion;
8071                    mAndroidApplication = pkg.applicationInfo;
8072
8073                    if (!mResolverReplaced) {
8074                        mResolveActivity.applicationInfo = mAndroidApplication;
8075                        mResolveActivity.name = ResolverActivity.class.getName();
8076                        mResolveActivity.packageName = mAndroidApplication.packageName;
8077                        mResolveActivity.processName = "system:ui";
8078                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8079                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8080                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8081                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8082                        mResolveActivity.exported = true;
8083                        mResolveActivity.enabled = true;
8084                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8085                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8086                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8087                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8088                                | ActivityInfo.CONFIG_ORIENTATION
8089                                | ActivityInfo.CONFIG_KEYBOARD
8090                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8091                        mResolveInfo.activityInfo = mResolveActivity;
8092                        mResolveInfo.priority = 0;
8093                        mResolveInfo.preferredOrder = 0;
8094                        mResolveInfo.match = 0;
8095                        mResolveComponentName = new ComponentName(
8096                                mAndroidApplication.packageName, mResolveActivity.name);
8097                    }
8098                }
8099            }
8100        }
8101
8102        if (DEBUG_PACKAGE_SCANNING) {
8103            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8104                Log.d(TAG, "Scanning package " + pkg.packageName);
8105        }
8106
8107        synchronized (mPackages) {
8108            if (mPackages.containsKey(pkg.packageName)
8109                    || mSharedLibraries.containsKey(pkg.packageName)) {
8110                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8111                        "Application package " + pkg.packageName
8112                                + " already installed.  Skipping duplicate.");
8113            }
8114
8115            // If we're only installing presumed-existing packages, require that the
8116            // scanned APK is both already known and at the path previously established
8117            // for it.  Previously unknown packages we pick up normally, but if we have an
8118            // a priori expectation about this package's install presence, enforce it.
8119            // With a singular exception for new system packages. When an OTA contains
8120            // a new system package, we allow the codepath to change from a system location
8121            // to the user-installed location. If we don't allow this change, any newer,
8122            // user-installed version of the application will be ignored.
8123            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8124                if (mExpectingBetter.containsKey(pkg.packageName)) {
8125                    logCriticalInfo(Log.WARN,
8126                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8127                } else {
8128                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8129                    if (known != null) {
8130                        if (DEBUG_PACKAGE_SCANNING) {
8131                            Log.d(TAG, "Examining " + pkg.codePath
8132                                    + " and requiring known paths " + known.codePathString
8133                                    + " & " + known.resourcePathString);
8134                        }
8135                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8136                                || !pkg.applicationInfo.getResourcePath().equals(
8137                                known.resourcePathString)) {
8138                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8139                                    "Application package " + pkg.packageName
8140                                            + " found at " + pkg.applicationInfo.getCodePath()
8141                                            + " but expected at " + known.codePathString
8142                                            + "; ignoring.");
8143                        }
8144                    }
8145                }
8146            }
8147        }
8148
8149        // Initialize package source and resource directories
8150        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8151        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8152
8153        SharedUserSetting suid = null;
8154        PackageSetting pkgSetting = null;
8155
8156        if (!isSystemApp(pkg)) {
8157            // Only system apps can use these features.
8158            pkg.mOriginalPackages = null;
8159            pkg.mRealPackage = null;
8160            pkg.mAdoptPermissions = null;
8161        }
8162
8163        // Getting the package setting may have a side-effect, so if we
8164        // are only checking if scan would succeed, stash a copy of the
8165        // old setting to restore at the end.
8166        PackageSetting nonMutatedPs = null;
8167
8168        // writer
8169        synchronized (mPackages) {
8170            if (pkg.mSharedUserId != null) {
8171                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8172                if (suid == null) {
8173                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8174                            "Creating application package " + pkg.packageName
8175                            + " for shared user failed");
8176                }
8177                if (DEBUG_PACKAGE_SCANNING) {
8178                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8179                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8180                                + "): packages=" + suid.packages);
8181                }
8182            }
8183
8184            // Check if we are renaming from an original package name.
8185            PackageSetting origPackage = null;
8186            String realName = null;
8187            if (pkg.mOriginalPackages != null) {
8188                // This package may need to be renamed to a previously
8189                // installed name.  Let's check on that...
8190                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8191                if (pkg.mOriginalPackages.contains(renamed)) {
8192                    // This package had originally been installed as the
8193                    // original name, and we have already taken care of
8194                    // transitioning to the new one.  Just update the new
8195                    // one to continue using the old name.
8196                    realName = pkg.mRealPackage;
8197                    if (!pkg.packageName.equals(renamed)) {
8198                        // Callers into this function may have already taken
8199                        // care of renaming the package; only do it here if
8200                        // it is not already done.
8201                        pkg.setPackageName(renamed);
8202                    }
8203
8204                } else {
8205                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8206                        if ((origPackage = mSettings.peekPackageLPr(
8207                                pkg.mOriginalPackages.get(i))) != null) {
8208                            // We do have the package already installed under its
8209                            // original name...  should we use it?
8210                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8211                                // New package is not compatible with original.
8212                                origPackage = null;
8213                                continue;
8214                            } else if (origPackage.sharedUser != null) {
8215                                // Make sure uid is compatible between packages.
8216                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8217                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8218                                            + " to " + pkg.packageName + ": old uid "
8219                                            + origPackage.sharedUser.name
8220                                            + " differs from " + pkg.mSharedUserId);
8221                                    origPackage = null;
8222                                    continue;
8223                                }
8224                                // TODO: Add case when shared user id is added [b/28144775]
8225                            } else {
8226                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8227                                        + pkg.packageName + " to old name " + origPackage.name);
8228                            }
8229                            break;
8230                        }
8231                    }
8232                }
8233            }
8234
8235            if (mTransferedPackages.contains(pkg.packageName)) {
8236                Slog.w(TAG, "Package " + pkg.packageName
8237                        + " was transferred to another, but its .apk remains");
8238            }
8239
8240            // See comments in nonMutatedPs declaration
8241            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8242                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8243                if (foundPs != null) {
8244                    nonMutatedPs = new PackageSetting(foundPs);
8245                }
8246            }
8247
8248            // Just create the setting, don't add it yet. For already existing packages
8249            // the PkgSetting exists already and doesn't have to be created.
8250            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8251                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8252                    pkg.applicationInfo.primaryCpuAbi,
8253                    pkg.applicationInfo.secondaryCpuAbi,
8254                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8255                    user, false);
8256            if (pkgSetting == null) {
8257                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8258                        "Creating application package " + pkg.packageName + " failed");
8259            }
8260
8261            if (pkgSetting.origPackage != null) {
8262                // If we are first transitioning from an original package,
8263                // fix up the new package's name now.  We need to do this after
8264                // looking up the package under its new name, so getPackageLP
8265                // can take care of fiddling things correctly.
8266                pkg.setPackageName(origPackage.name);
8267
8268                // File a report about this.
8269                String msg = "New package " + pkgSetting.realName
8270                        + " renamed to replace old package " + pkgSetting.name;
8271                reportSettingsProblem(Log.WARN, msg);
8272
8273                // Make a note of it.
8274                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8275                    mTransferedPackages.add(origPackage.name);
8276                }
8277
8278                // No longer need to retain this.
8279                pkgSetting.origPackage = null;
8280            }
8281
8282            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8283                // Make a note of it.
8284                mTransferedPackages.add(pkg.packageName);
8285            }
8286
8287            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8288                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8289            }
8290
8291            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8292                // Check all shared libraries and map to their actual file path.
8293                // We only do this here for apps not on a system dir, because those
8294                // are the only ones that can fail an install due to this.  We
8295                // will take care of the system apps by updating all of their
8296                // library paths after the scan is done.
8297                updateSharedLibrariesLPw(pkg, null);
8298            }
8299
8300            if (mFoundPolicyFile) {
8301                SELinuxMMAC.assignSeinfoValue(pkg);
8302            }
8303
8304            pkg.applicationInfo.uid = pkgSetting.appId;
8305            pkg.mExtras = pkgSetting;
8306            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8307                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8308                    // We just determined the app is signed correctly, so bring
8309                    // over the latest parsed certs.
8310                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8311                } else {
8312                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8313                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8314                                "Package " + pkg.packageName + " upgrade keys do not match the "
8315                                + "previously installed version");
8316                    } else {
8317                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8318                        String msg = "System package " + pkg.packageName
8319                            + " signature changed; retaining data.";
8320                        reportSettingsProblem(Log.WARN, msg);
8321                    }
8322                }
8323            } else {
8324                try {
8325                    verifySignaturesLP(pkgSetting, pkg);
8326                    // We just determined the app is signed correctly, so bring
8327                    // over the latest parsed certs.
8328                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8329                } catch (PackageManagerException e) {
8330                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8331                        throw e;
8332                    }
8333                    // The signature has changed, but this package is in the system
8334                    // image...  let's recover!
8335                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8336                    // However...  if this package is part of a shared user, but it
8337                    // doesn't match the signature of the shared user, let's fail.
8338                    // What this means is that you can't change the signatures
8339                    // associated with an overall shared user, which doesn't seem all
8340                    // that unreasonable.
8341                    if (pkgSetting.sharedUser != null) {
8342                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8343                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8344                            throw new PackageManagerException(
8345                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8346                                            "Signature mismatch for shared user: "
8347                                            + pkgSetting.sharedUser);
8348                        }
8349                    }
8350                    // File a report about this.
8351                    String msg = "System package " + pkg.packageName
8352                        + " signature changed; retaining data.";
8353                    reportSettingsProblem(Log.WARN, msg);
8354                }
8355            }
8356            // Verify that this new package doesn't have any content providers
8357            // that conflict with existing packages.  Only do this if the
8358            // package isn't already installed, since we don't want to break
8359            // things that are installed.
8360            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8361                final int N = pkg.providers.size();
8362                int i;
8363                for (i=0; i<N; i++) {
8364                    PackageParser.Provider p = pkg.providers.get(i);
8365                    if (p.info.authority != null) {
8366                        String names[] = p.info.authority.split(";");
8367                        for (int j = 0; j < names.length; j++) {
8368                            if (mProvidersByAuthority.containsKey(names[j])) {
8369                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8370                                final String otherPackageName =
8371                                        ((other != null && other.getComponentName() != null) ?
8372                                                other.getComponentName().getPackageName() : "?");
8373                                throw new PackageManagerException(
8374                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8375                                                "Can't install because provider name " + names[j]
8376                                                + " (in package " + pkg.applicationInfo.packageName
8377                                                + ") is already used by " + otherPackageName);
8378                            }
8379                        }
8380                    }
8381                }
8382            }
8383
8384            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8385                // This package wants to adopt ownership of permissions from
8386                // another package.
8387                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8388                    final String origName = pkg.mAdoptPermissions.get(i);
8389                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8390                    if (orig != null) {
8391                        if (verifyPackageUpdateLPr(orig, pkg)) {
8392                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8393                                    + pkg.packageName);
8394                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8395                        }
8396                    }
8397                }
8398            }
8399        }
8400
8401        final String pkgName = pkg.packageName;
8402
8403        final long scanFileTime = scanFile.lastModified();
8404        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8405        pkg.applicationInfo.processName = fixProcessName(
8406                pkg.applicationInfo.packageName,
8407                pkg.applicationInfo.processName,
8408                pkg.applicationInfo.uid);
8409
8410        if (pkg != mPlatformPackage) {
8411            // Get all of our default paths setup
8412            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8413        }
8414
8415        final String path = scanFile.getPath();
8416        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8417
8418        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8419            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8420
8421            // Some system apps still use directory structure for native libraries
8422            // in which case we might end up not detecting abi solely based on apk
8423            // structure. Try to detect abi based on directory structure.
8424            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8425                    pkg.applicationInfo.primaryCpuAbi == null) {
8426                setBundledAppAbisAndRoots(pkg, pkgSetting);
8427                setNativeLibraryPaths(pkg);
8428            }
8429
8430        } else {
8431            if ((scanFlags & SCAN_MOVE) != 0) {
8432                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8433                // but we already have this packages package info in the PackageSetting. We just
8434                // use that and derive the native library path based on the new codepath.
8435                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8436                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8437            }
8438
8439            // Set native library paths again. For moves, the path will be updated based on the
8440            // ABIs we've determined above. For non-moves, the path will be updated based on the
8441            // ABIs we determined during compilation, but the path will depend on the final
8442            // package path (after the rename away from the stage path).
8443            setNativeLibraryPaths(pkg);
8444        }
8445
8446        // This is a special case for the "system" package, where the ABI is
8447        // dictated by the zygote configuration (and init.rc). We should keep track
8448        // of this ABI so that we can deal with "normal" applications that run under
8449        // the same UID correctly.
8450        if (mPlatformPackage == pkg) {
8451            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8452                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8453        }
8454
8455        // If there's a mismatch between the abi-override in the package setting
8456        // and the abiOverride specified for the install. Warn about this because we
8457        // would've already compiled the app without taking the package setting into
8458        // account.
8459        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8460            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8461                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8462                        " for package " + pkg.packageName);
8463            }
8464        }
8465
8466        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8467        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8468        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8469
8470        // Copy the derived override back to the parsed package, so that we can
8471        // update the package settings accordingly.
8472        pkg.cpuAbiOverride = cpuAbiOverride;
8473
8474        if (DEBUG_ABI_SELECTION) {
8475            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8476                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8477                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8478        }
8479
8480        // Push the derived path down into PackageSettings so we know what to
8481        // clean up at uninstall time.
8482        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8483
8484        if (DEBUG_ABI_SELECTION) {
8485            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8486                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8487                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8488        }
8489
8490        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8491            // We don't do this here during boot because we can do it all
8492            // at once after scanning all existing packages.
8493            //
8494            // We also do this *before* we perform dexopt on this package, so that
8495            // we can avoid redundant dexopts, and also to make sure we've got the
8496            // code and package path correct.
8497            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8498                    pkg, true /* boot complete */);
8499        }
8500
8501        if (mFactoryTest && pkg.requestedPermissions.contains(
8502                android.Manifest.permission.FACTORY_TEST)) {
8503            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8504        }
8505
8506        ArrayList<PackageParser.Package> clientLibPkgs = null;
8507
8508        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8509            if (nonMutatedPs != null) {
8510                synchronized (mPackages) {
8511                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8512                }
8513            }
8514            return pkg;
8515        }
8516
8517        // Only privileged apps and updated privileged apps can add child packages.
8518        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8519            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8520                throw new PackageManagerException("Only privileged apps and updated "
8521                        + "privileged apps can add child packages. Ignoring package "
8522                        + pkg.packageName);
8523            }
8524            final int childCount = pkg.childPackages.size();
8525            for (int i = 0; i < childCount; i++) {
8526                PackageParser.Package childPkg = pkg.childPackages.get(i);
8527                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8528                        childPkg.packageName)) {
8529                    throw new PackageManagerException("Cannot override a child package of "
8530                            + "another disabled system app. Ignoring package " + pkg.packageName);
8531                }
8532            }
8533        }
8534
8535        // writer
8536        synchronized (mPackages) {
8537            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8538                // Only system apps can add new shared libraries.
8539                if (pkg.libraryNames != null) {
8540                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8541                        String name = pkg.libraryNames.get(i);
8542                        boolean allowed = false;
8543                        if (pkg.isUpdatedSystemApp()) {
8544                            // New library entries can only be added through the
8545                            // system image.  This is important to get rid of a lot
8546                            // of nasty edge cases: for example if we allowed a non-
8547                            // system update of the app to add a library, then uninstalling
8548                            // the update would make the library go away, and assumptions
8549                            // we made such as through app install filtering would now
8550                            // have allowed apps on the device which aren't compatible
8551                            // with it.  Better to just have the restriction here, be
8552                            // conservative, and create many fewer cases that can negatively
8553                            // impact the user experience.
8554                            final PackageSetting sysPs = mSettings
8555                                    .getDisabledSystemPkgLPr(pkg.packageName);
8556                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8557                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8558                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8559                                        allowed = true;
8560                                        break;
8561                                    }
8562                                }
8563                            }
8564                        } else {
8565                            allowed = true;
8566                        }
8567                        if (allowed) {
8568                            if (!mSharedLibraries.containsKey(name)) {
8569                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8570                            } else if (!name.equals(pkg.packageName)) {
8571                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8572                                        + name + " already exists; skipping");
8573                            }
8574                        } else {
8575                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8576                                    + name + " that is not declared on system image; skipping");
8577                        }
8578                    }
8579                    if ((scanFlags & SCAN_BOOTING) == 0) {
8580                        // If we are not booting, we need to update any applications
8581                        // that are clients of our shared library.  If we are booting,
8582                        // this will all be done once the scan is complete.
8583                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8584                    }
8585                }
8586            }
8587        }
8588
8589        if ((scanFlags & SCAN_BOOTING) != 0) {
8590            // No apps can run during boot scan, so they don't need to be frozen
8591        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8592            // Caller asked to not kill app, so it's probably not frozen
8593        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8594            // Caller asked us to ignore frozen check for some reason; they
8595            // probably didn't know the package name
8596        } else {
8597            // We're doing major surgery on this package, so it better be frozen
8598            // right now to keep it from launching
8599            checkPackageFrozen(pkgName);
8600        }
8601
8602        // Also need to kill any apps that are dependent on the library.
8603        if (clientLibPkgs != null) {
8604            for (int i=0; i<clientLibPkgs.size(); i++) {
8605                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8606                killApplication(clientPkg.applicationInfo.packageName,
8607                        clientPkg.applicationInfo.uid, "update lib");
8608            }
8609        }
8610
8611        // Make sure we're not adding any bogus keyset info
8612        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8613        ksms.assertScannedPackageValid(pkg);
8614
8615        // writer
8616        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8617
8618        boolean createIdmapFailed = false;
8619        synchronized (mPackages) {
8620            // We don't expect installation to fail beyond this point
8621
8622            if (pkgSetting.pkg != null) {
8623                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, user);
8624            }
8625
8626            // Add the new setting to mSettings
8627            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8628            // Add the new setting to mPackages
8629            mPackages.put(pkg.applicationInfo.packageName, pkg);
8630            // Make sure we don't accidentally delete its data.
8631            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8632            while (iter.hasNext()) {
8633                PackageCleanItem item = iter.next();
8634                if (pkgName.equals(item.packageName)) {
8635                    iter.remove();
8636                }
8637            }
8638
8639            // Take care of first install / last update times.
8640            if (currentTime != 0) {
8641                if (pkgSetting.firstInstallTime == 0) {
8642                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8643                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8644                    pkgSetting.lastUpdateTime = currentTime;
8645                }
8646            } else if (pkgSetting.firstInstallTime == 0) {
8647                // We need *something*.  Take time time stamp of the file.
8648                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8649            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8650                if (scanFileTime != pkgSetting.timeStamp) {
8651                    // A package on the system image has changed; consider this
8652                    // to be an update.
8653                    pkgSetting.lastUpdateTime = scanFileTime;
8654                }
8655            }
8656
8657            // Add the package's KeySets to the global KeySetManagerService
8658            ksms.addScannedPackageLPw(pkg);
8659
8660            int N = pkg.providers.size();
8661            StringBuilder r = null;
8662            int i;
8663            for (i=0; i<N; i++) {
8664                PackageParser.Provider p = pkg.providers.get(i);
8665                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8666                        p.info.processName, pkg.applicationInfo.uid);
8667                mProviders.addProvider(p);
8668                p.syncable = p.info.isSyncable;
8669                if (p.info.authority != null) {
8670                    String names[] = p.info.authority.split(";");
8671                    p.info.authority = null;
8672                    for (int j = 0; j < names.length; j++) {
8673                        if (j == 1 && p.syncable) {
8674                            // We only want the first authority for a provider to possibly be
8675                            // syncable, so if we already added this provider using a different
8676                            // authority clear the syncable flag. We copy the provider before
8677                            // changing it because the mProviders object contains a reference
8678                            // to a provider that we don't want to change.
8679                            // Only do this for the second authority since the resulting provider
8680                            // object can be the same for all future authorities for this provider.
8681                            p = new PackageParser.Provider(p);
8682                            p.syncable = false;
8683                        }
8684                        if (!mProvidersByAuthority.containsKey(names[j])) {
8685                            mProvidersByAuthority.put(names[j], p);
8686                            if (p.info.authority == null) {
8687                                p.info.authority = names[j];
8688                            } else {
8689                                p.info.authority = p.info.authority + ";" + names[j];
8690                            }
8691                            if (DEBUG_PACKAGE_SCANNING) {
8692                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8693                                    Log.d(TAG, "Registered content provider: " + names[j]
8694                                            + ", className = " + p.info.name + ", isSyncable = "
8695                                            + p.info.isSyncable);
8696                            }
8697                        } else {
8698                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8699                            Slog.w(TAG, "Skipping provider name " + names[j] +
8700                                    " (in package " + pkg.applicationInfo.packageName +
8701                                    "): name already used by "
8702                                    + ((other != null && other.getComponentName() != null)
8703                                            ? other.getComponentName().getPackageName() : "?"));
8704                        }
8705                    }
8706                }
8707                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8708                    if (r == null) {
8709                        r = new StringBuilder(256);
8710                    } else {
8711                        r.append(' ');
8712                    }
8713                    r.append(p.info.name);
8714                }
8715            }
8716            if (r != null) {
8717                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8718            }
8719
8720            N = pkg.services.size();
8721            r = null;
8722            for (i=0; i<N; i++) {
8723                PackageParser.Service s = pkg.services.get(i);
8724                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8725                        s.info.processName, pkg.applicationInfo.uid);
8726                mServices.addService(s);
8727                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8728                    if (r == null) {
8729                        r = new StringBuilder(256);
8730                    } else {
8731                        r.append(' ');
8732                    }
8733                    r.append(s.info.name);
8734                }
8735            }
8736            if (r != null) {
8737                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8738            }
8739
8740            N = pkg.receivers.size();
8741            r = null;
8742            for (i=0; i<N; i++) {
8743                PackageParser.Activity a = pkg.receivers.get(i);
8744                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8745                        a.info.processName, pkg.applicationInfo.uid);
8746                mReceivers.addActivity(a, "receiver");
8747                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8748                    if (r == null) {
8749                        r = new StringBuilder(256);
8750                    } else {
8751                        r.append(' ');
8752                    }
8753                    r.append(a.info.name);
8754                }
8755            }
8756            if (r != null) {
8757                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8758            }
8759
8760            N = pkg.activities.size();
8761            r = null;
8762            for (i=0; i<N; i++) {
8763                PackageParser.Activity a = pkg.activities.get(i);
8764                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8765                        a.info.processName, pkg.applicationInfo.uid);
8766                mActivities.addActivity(a, "activity");
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(a.info.name);
8774                }
8775            }
8776            if (r != null) {
8777                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8778            }
8779
8780            N = pkg.permissionGroups.size();
8781            r = null;
8782            for (i=0; i<N; i++) {
8783                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8784                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8785                if (cur == null) {
8786                    mPermissionGroups.put(pg.info.name, pg);
8787                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8788                        if (r == null) {
8789                            r = new StringBuilder(256);
8790                        } else {
8791                            r.append(' ');
8792                        }
8793                        r.append(pg.info.name);
8794                    }
8795                } else {
8796                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8797                            + pg.info.packageName + " ignored: original from "
8798                            + cur.info.packageName);
8799                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8800                        if (r == null) {
8801                            r = new StringBuilder(256);
8802                        } else {
8803                            r.append(' ');
8804                        }
8805                        r.append("DUP:");
8806                        r.append(pg.info.name);
8807                    }
8808                }
8809            }
8810            if (r != null) {
8811                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8812            }
8813
8814            N = pkg.permissions.size();
8815            r = null;
8816            for (i=0; i<N; i++) {
8817                PackageParser.Permission p = pkg.permissions.get(i);
8818
8819                // Assume by default that we did not install this permission into the system.
8820                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8821
8822                // Now that permission groups have a special meaning, we ignore permission
8823                // groups for legacy apps to prevent unexpected behavior. In particular,
8824                // permissions for one app being granted to someone just becase they happen
8825                // to be in a group defined by another app (before this had no implications).
8826                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8827                    p.group = mPermissionGroups.get(p.info.group);
8828                    // Warn for a permission in an unknown group.
8829                    if (p.info.group != null && p.group == null) {
8830                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8831                                + p.info.packageName + " in an unknown group " + p.info.group);
8832                    }
8833                }
8834
8835                ArrayMap<String, BasePermission> permissionMap =
8836                        p.tree ? mSettings.mPermissionTrees
8837                                : mSettings.mPermissions;
8838                BasePermission bp = permissionMap.get(p.info.name);
8839
8840                // Allow system apps to redefine non-system permissions
8841                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8842                    final boolean currentOwnerIsSystem = (bp.perm != null
8843                            && isSystemApp(bp.perm.owner));
8844                    if (isSystemApp(p.owner)) {
8845                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8846                            // It's a built-in permission and no owner, take ownership now
8847                            bp.packageSetting = pkgSetting;
8848                            bp.perm = p;
8849                            bp.uid = pkg.applicationInfo.uid;
8850                            bp.sourcePackage = p.info.packageName;
8851                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8852                        } else if (!currentOwnerIsSystem) {
8853                            String msg = "New decl " + p.owner + " of permission  "
8854                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8855                            reportSettingsProblem(Log.WARN, msg);
8856                            bp = null;
8857                        }
8858                    }
8859                }
8860
8861                if (bp == null) {
8862                    bp = new BasePermission(p.info.name, p.info.packageName,
8863                            BasePermission.TYPE_NORMAL);
8864                    permissionMap.put(p.info.name, bp);
8865                }
8866
8867                if (bp.perm == null) {
8868                    if (bp.sourcePackage == null
8869                            || bp.sourcePackage.equals(p.info.packageName)) {
8870                        BasePermission tree = findPermissionTreeLP(p.info.name);
8871                        if (tree == null
8872                                || tree.sourcePackage.equals(p.info.packageName)) {
8873                            bp.packageSetting = pkgSetting;
8874                            bp.perm = p;
8875                            bp.uid = pkg.applicationInfo.uid;
8876                            bp.sourcePackage = p.info.packageName;
8877                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8878                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8879                                if (r == null) {
8880                                    r = new StringBuilder(256);
8881                                } else {
8882                                    r.append(' ');
8883                                }
8884                                r.append(p.info.name);
8885                            }
8886                        } else {
8887                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8888                                    + p.info.packageName + " ignored: base tree "
8889                                    + tree.name + " is from package "
8890                                    + tree.sourcePackage);
8891                        }
8892                    } else {
8893                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8894                                + p.info.packageName + " ignored: original from "
8895                                + bp.sourcePackage);
8896                    }
8897                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8898                    if (r == null) {
8899                        r = new StringBuilder(256);
8900                    } else {
8901                        r.append(' ');
8902                    }
8903                    r.append("DUP:");
8904                    r.append(p.info.name);
8905                }
8906                if (bp.perm == p) {
8907                    bp.protectionLevel = p.info.protectionLevel;
8908                }
8909            }
8910
8911            if (r != null) {
8912                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8913            }
8914
8915            N = pkg.instrumentation.size();
8916            r = null;
8917            for (i=0; i<N; i++) {
8918                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8919                a.info.packageName = pkg.applicationInfo.packageName;
8920                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8921                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8922                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8923                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8924                a.info.dataDir = pkg.applicationInfo.dataDir;
8925                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8926                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8927
8928                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8929                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8930                mInstrumentation.put(a.getComponentName(), a);
8931                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8932                    if (r == null) {
8933                        r = new StringBuilder(256);
8934                    } else {
8935                        r.append(' ');
8936                    }
8937                    r.append(a.info.name);
8938                }
8939            }
8940            if (r != null) {
8941                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8942            }
8943
8944            if (pkg.protectedBroadcasts != null) {
8945                N = pkg.protectedBroadcasts.size();
8946                for (i=0; i<N; i++) {
8947                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8948                }
8949            }
8950
8951            pkgSetting.setTimeStamp(scanFileTime);
8952
8953            // Create idmap files for pairs of (packages, overlay packages).
8954            // Note: "android", ie framework-res.apk, is handled by native layers.
8955            if (pkg.mOverlayTarget != null) {
8956                // This is an overlay package.
8957                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8958                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8959                        mOverlays.put(pkg.mOverlayTarget,
8960                                new ArrayMap<String, PackageParser.Package>());
8961                    }
8962                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8963                    map.put(pkg.packageName, pkg);
8964                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8965                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8966                        createIdmapFailed = true;
8967                    }
8968                }
8969            } else if (mOverlays.containsKey(pkg.packageName) &&
8970                    !pkg.packageName.equals("android")) {
8971                // This is a regular package, with one or more known overlay packages.
8972                createIdmapsForPackageLI(pkg);
8973            }
8974        }
8975
8976        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8977
8978        if (createIdmapFailed) {
8979            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8980                    "scanPackageLI failed to createIdmap");
8981        }
8982        return pkg;
8983    }
8984
8985    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
8986            PackageParser.Package update, UserHandle user) {
8987        if (existing.applicationInfo == null || update.applicationInfo == null) {
8988            // This isn't due to an app installation.
8989            return;
8990        }
8991
8992        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
8993        final File newCodePath = new File(update.applicationInfo.getCodePath());
8994
8995        // The codePath hasn't changed, so there's nothing for us to do.
8996        if (Objects.equals(oldCodePath, newCodePath)) {
8997            return;
8998        }
8999
9000        File canonicalNewCodePath;
9001        try {
9002            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9003        } catch (IOException e) {
9004            Slog.w(TAG, "Failed to get canonical path.", e);
9005            return;
9006        }
9007
9008        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9009        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9010        // that the last component of the path (i.e, the name) doesn't need canonicalization
9011        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9012        // but may change in the future. Hopefully this function won't exist at that point.
9013        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9014                oldCodePath.getName());
9015
9016        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9017        // with "@".
9018        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9019        if (!oldMarkerPrefix.endsWith("@")) {
9020            oldMarkerPrefix += "@";
9021        }
9022        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9023        if (!newMarkerPrefix.endsWith("@")) {
9024            newMarkerPrefix += "@";
9025        }
9026
9027        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9028        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9029        for (String updatedPath : updatedPaths) {
9030            String updatedPathName = new File(updatedPath).getName();
9031            markerSuffixes.add(updatedPathName.replace('/', '@'));
9032        }
9033
9034        for (int userId : resolveUserIds(user.getIdentifier())) {
9035            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9036
9037            for (String markerSuffix : markerSuffixes) {
9038                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9039                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9040                if (oldForeignUseMark.exists()) {
9041                    try {
9042                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9043                                newForeignUseMark.getAbsolutePath());
9044                    } catch (ErrnoException e) {
9045                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9046                        oldForeignUseMark.delete();
9047                    }
9048                }
9049            }
9050        }
9051    }
9052
9053    /**
9054     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9055     * is derived purely on the basis of the contents of {@code scanFile} and
9056     * {@code cpuAbiOverride}.
9057     *
9058     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9059     */
9060    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9061                                 String cpuAbiOverride, boolean extractLibs)
9062            throws PackageManagerException {
9063        // TODO: We can probably be smarter about this stuff. For installed apps,
9064        // we can calculate this information at install time once and for all. For
9065        // system apps, we can probably assume that this information doesn't change
9066        // after the first boot scan. As things stand, we do lots of unnecessary work.
9067
9068        // Give ourselves some initial paths; we'll come back for another
9069        // pass once we've determined ABI below.
9070        setNativeLibraryPaths(pkg);
9071
9072        // We would never need to extract libs for forward-locked and external packages,
9073        // since the container service will do it for us. We shouldn't attempt to
9074        // extract libs from system app when it was not updated.
9075        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9076                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9077            extractLibs = false;
9078        }
9079
9080        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9081        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9082
9083        NativeLibraryHelper.Handle handle = null;
9084        try {
9085            handle = NativeLibraryHelper.Handle.create(pkg);
9086            // TODO(multiArch): This can be null for apps that didn't go through the
9087            // usual installation process. We can calculate it again, like we
9088            // do during install time.
9089            //
9090            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9091            // unnecessary.
9092            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9093
9094            // Null out the abis so that they can be recalculated.
9095            pkg.applicationInfo.primaryCpuAbi = null;
9096            pkg.applicationInfo.secondaryCpuAbi = null;
9097            if (isMultiArch(pkg.applicationInfo)) {
9098                // Warn if we've set an abiOverride for multi-lib packages..
9099                // By definition, we need to copy both 32 and 64 bit libraries for
9100                // such packages.
9101                if (pkg.cpuAbiOverride != null
9102                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9103                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9104                }
9105
9106                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9107                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9108                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9109                    if (extractLibs) {
9110                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9111                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9112                                useIsaSpecificSubdirs);
9113                    } else {
9114                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9115                    }
9116                }
9117
9118                maybeThrowExceptionForMultiArchCopy(
9119                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9120
9121                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9122                    if (extractLibs) {
9123                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9124                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9125                                useIsaSpecificSubdirs);
9126                    } else {
9127                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9128                    }
9129                }
9130
9131                maybeThrowExceptionForMultiArchCopy(
9132                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9133
9134                if (abi64 >= 0) {
9135                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9136                }
9137
9138                if (abi32 >= 0) {
9139                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9140                    if (abi64 >= 0) {
9141                        if (pkg.use32bitAbi) {
9142                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9143                            pkg.applicationInfo.primaryCpuAbi = abi;
9144                        } else {
9145                            pkg.applicationInfo.secondaryCpuAbi = abi;
9146                        }
9147                    } else {
9148                        pkg.applicationInfo.primaryCpuAbi = abi;
9149                    }
9150                }
9151
9152            } else {
9153                String[] abiList = (cpuAbiOverride != null) ?
9154                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9155
9156                // Enable gross and lame hacks for apps that are built with old
9157                // SDK tools. We must scan their APKs for renderscript bitcode and
9158                // not launch them if it's present. Don't bother checking on devices
9159                // that don't have 64 bit support.
9160                boolean needsRenderScriptOverride = false;
9161                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9162                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9163                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9164                    needsRenderScriptOverride = true;
9165                }
9166
9167                final int copyRet;
9168                if (extractLibs) {
9169                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9170                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9171                } else {
9172                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9173                }
9174
9175                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9176                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9177                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9178                }
9179
9180                if (copyRet >= 0) {
9181                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9182                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9183                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9184                } else if (needsRenderScriptOverride) {
9185                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9186                }
9187            }
9188        } catch (IOException ioe) {
9189            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9190        } finally {
9191            IoUtils.closeQuietly(handle);
9192        }
9193
9194        // Now that we've calculated the ABIs and determined if it's an internal app,
9195        // we will go ahead and populate the nativeLibraryPath.
9196        setNativeLibraryPaths(pkg);
9197    }
9198
9199    /**
9200     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9201     * i.e, so that all packages can be run inside a single process if required.
9202     *
9203     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9204     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9205     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9206     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9207     * updating a package that belongs to a shared user.
9208     *
9209     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9210     * adds unnecessary complexity.
9211     */
9212    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9213            PackageParser.Package scannedPackage, boolean bootComplete) {
9214        String requiredInstructionSet = null;
9215        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9216            requiredInstructionSet = VMRuntime.getInstructionSet(
9217                     scannedPackage.applicationInfo.primaryCpuAbi);
9218        }
9219
9220        PackageSetting requirer = null;
9221        for (PackageSetting ps : packagesForUser) {
9222            // If packagesForUser contains scannedPackage, we skip it. This will happen
9223            // when scannedPackage is an update of an existing package. Without this check,
9224            // we will never be able to change the ABI of any package belonging to a shared
9225            // user, even if it's compatible with other packages.
9226            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9227                if (ps.primaryCpuAbiString == null) {
9228                    continue;
9229                }
9230
9231                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9232                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9233                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9234                    // this but there's not much we can do.
9235                    String errorMessage = "Instruction set mismatch, "
9236                            + ((requirer == null) ? "[caller]" : requirer)
9237                            + " requires " + requiredInstructionSet + " whereas " + ps
9238                            + " requires " + instructionSet;
9239                    Slog.w(TAG, errorMessage);
9240                }
9241
9242                if (requiredInstructionSet == null) {
9243                    requiredInstructionSet = instructionSet;
9244                    requirer = ps;
9245                }
9246            }
9247        }
9248
9249        if (requiredInstructionSet != null) {
9250            String adjustedAbi;
9251            if (requirer != null) {
9252                // requirer != null implies that either scannedPackage was null or that scannedPackage
9253                // did not require an ABI, in which case we have to adjust scannedPackage to match
9254                // the ABI of the set (which is the same as requirer's ABI)
9255                adjustedAbi = requirer.primaryCpuAbiString;
9256                if (scannedPackage != null) {
9257                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9258                }
9259            } else {
9260                // requirer == null implies that we're updating all ABIs in the set to
9261                // match scannedPackage.
9262                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9263            }
9264
9265            for (PackageSetting ps : packagesForUser) {
9266                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9267                    if (ps.primaryCpuAbiString != null) {
9268                        continue;
9269                    }
9270
9271                    ps.primaryCpuAbiString = adjustedAbi;
9272                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9273                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9274                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9275                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9276                                + " (requirer="
9277                                + (requirer == null ? "null" : requirer.pkg.packageName)
9278                                + ", scannedPackage="
9279                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9280                                + ")");
9281                        try {
9282                            mInstaller.rmdex(ps.codePathString,
9283                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9284                        } catch (InstallerException ignored) {
9285                        }
9286                    }
9287                }
9288            }
9289        }
9290    }
9291
9292    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9293        synchronized (mPackages) {
9294            mResolverReplaced = true;
9295            // Set up information for custom user intent resolution activity.
9296            mResolveActivity.applicationInfo = pkg.applicationInfo;
9297            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9298            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9299            mResolveActivity.processName = pkg.applicationInfo.packageName;
9300            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9301            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9302                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9303            mResolveActivity.theme = 0;
9304            mResolveActivity.exported = true;
9305            mResolveActivity.enabled = true;
9306            mResolveInfo.activityInfo = mResolveActivity;
9307            mResolveInfo.priority = 0;
9308            mResolveInfo.preferredOrder = 0;
9309            mResolveInfo.match = 0;
9310            mResolveComponentName = mCustomResolverComponentName;
9311            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9312                    mResolveComponentName);
9313        }
9314    }
9315
9316    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9317        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9318
9319        // Set up information for ephemeral installer activity
9320        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9321        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9322        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9323        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9324        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9325        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9326                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9327        mEphemeralInstallerActivity.theme = 0;
9328        mEphemeralInstallerActivity.exported = true;
9329        mEphemeralInstallerActivity.enabled = true;
9330        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9331        mEphemeralInstallerInfo.priority = 0;
9332        mEphemeralInstallerInfo.preferredOrder = 0;
9333        mEphemeralInstallerInfo.match = 0;
9334
9335        if (DEBUG_EPHEMERAL) {
9336            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9337        }
9338    }
9339
9340    private static String calculateBundledApkRoot(final String codePathString) {
9341        final File codePath = new File(codePathString);
9342        final File codeRoot;
9343        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9344            codeRoot = Environment.getRootDirectory();
9345        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9346            codeRoot = Environment.getOemDirectory();
9347        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9348            codeRoot = Environment.getVendorDirectory();
9349        } else {
9350            // Unrecognized code path; take its top real segment as the apk root:
9351            // e.g. /something/app/blah.apk => /something
9352            try {
9353                File f = codePath.getCanonicalFile();
9354                File parent = f.getParentFile();    // non-null because codePath is a file
9355                File tmp;
9356                while ((tmp = parent.getParentFile()) != null) {
9357                    f = parent;
9358                    parent = tmp;
9359                }
9360                codeRoot = f;
9361                Slog.w(TAG, "Unrecognized code path "
9362                        + codePath + " - using " + codeRoot);
9363            } catch (IOException e) {
9364                // Can't canonicalize the code path -- shenanigans?
9365                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9366                return Environment.getRootDirectory().getPath();
9367            }
9368        }
9369        return codeRoot.getPath();
9370    }
9371
9372    /**
9373     * Derive and set the location of native libraries for the given package,
9374     * which varies depending on where and how the package was installed.
9375     */
9376    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9377        final ApplicationInfo info = pkg.applicationInfo;
9378        final String codePath = pkg.codePath;
9379        final File codeFile = new File(codePath);
9380        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9381        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9382
9383        info.nativeLibraryRootDir = null;
9384        info.nativeLibraryRootRequiresIsa = false;
9385        info.nativeLibraryDir = null;
9386        info.secondaryNativeLibraryDir = null;
9387
9388        if (isApkFile(codeFile)) {
9389            // Monolithic install
9390            if (bundledApp) {
9391                // If "/system/lib64/apkname" exists, assume that is the per-package
9392                // native library directory to use; otherwise use "/system/lib/apkname".
9393                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9394                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9395                        getPrimaryInstructionSet(info));
9396
9397                // This is a bundled system app so choose the path based on the ABI.
9398                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9399                // is just the default path.
9400                final String apkName = deriveCodePathName(codePath);
9401                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9402                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9403                        apkName).getAbsolutePath();
9404
9405                if (info.secondaryCpuAbi != null) {
9406                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9407                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9408                            secondaryLibDir, apkName).getAbsolutePath();
9409                }
9410            } else if (asecApp) {
9411                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9412                        .getAbsolutePath();
9413            } else {
9414                final String apkName = deriveCodePathName(codePath);
9415                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9416                        .getAbsolutePath();
9417            }
9418
9419            info.nativeLibraryRootRequiresIsa = false;
9420            info.nativeLibraryDir = info.nativeLibraryRootDir;
9421        } else {
9422            // Cluster install
9423            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9424            info.nativeLibraryRootRequiresIsa = true;
9425
9426            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9427                    getPrimaryInstructionSet(info)).getAbsolutePath();
9428
9429            if (info.secondaryCpuAbi != null) {
9430                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9431                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9432            }
9433        }
9434    }
9435
9436    /**
9437     * Calculate the abis and roots for a bundled app. These can uniquely
9438     * be determined from the contents of the system partition, i.e whether
9439     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9440     * of this information, and instead assume that the system was built
9441     * sensibly.
9442     */
9443    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9444                                           PackageSetting pkgSetting) {
9445        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9446
9447        // If "/system/lib64/apkname" exists, assume that is the per-package
9448        // native library directory to use; otherwise use "/system/lib/apkname".
9449        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9450        setBundledAppAbi(pkg, apkRoot, apkName);
9451        // pkgSetting might be null during rescan following uninstall of updates
9452        // to a bundled app, so accommodate that possibility.  The settings in
9453        // that case will be established later from the parsed package.
9454        //
9455        // If the settings aren't null, sync them up with what we've just derived.
9456        // note that apkRoot isn't stored in the package settings.
9457        if (pkgSetting != null) {
9458            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9459            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9460        }
9461    }
9462
9463    /**
9464     * Deduces the ABI of a bundled app and sets the relevant fields on the
9465     * parsed pkg object.
9466     *
9467     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9468     *        under which system libraries are installed.
9469     * @param apkName the name of the installed package.
9470     */
9471    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9472        final File codeFile = new File(pkg.codePath);
9473
9474        final boolean has64BitLibs;
9475        final boolean has32BitLibs;
9476        if (isApkFile(codeFile)) {
9477            // Monolithic install
9478            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9479            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9480        } else {
9481            // Cluster install
9482            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9483            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9484                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9485                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9486                has64BitLibs = (new File(rootDir, isa)).exists();
9487            } else {
9488                has64BitLibs = false;
9489            }
9490            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9491                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9492                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9493                has32BitLibs = (new File(rootDir, isa)).exists();
9494            } else {
9495                has32BitLibs = false;
9496            }
9497        }
9498
9499        if (has64BitLibs && !has32BitLibs) {
9500            // The package has 64 bit libs, but not 32 bit libs. Its primary
9501            // ABI should be 64 bit. We can safely assume here that the bundled
9502            // native libraries correspond to the most preferred ABI in the list.
9503
9504            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9505            pkg.applicationInfo.secondaryCpuAbi = null;
9506        } else if (has32BitLibs && !has64BitLibs) {
9507            // The package has 32 bit libs but not 64 bit libs. Its primary
9508            // ABI should be 32 bit.
9509
9510            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9511            pkg.applicationInfo.secondaryCpuAbi = null;
9512        } else if (has32BitLibs && has64BitLibs) {
9513            // The application has both 64 and 32 bit bundled libraries. We check
9514            // here that the app declares multiArch support, and warn if it doesn't.
9515            //
9516            // We will be lenient here and record both ABIs. The primary will be the
9517            // ABI that's higher on the list, i.e, a device that's configured to prefer
9518            // 64 bit apps will see a 64 bit primary ABI,
9519
9520            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9521                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9522            }
9523
9524            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9525                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9526                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9527            } else {
9528                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9529                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9530            }
9531        } else {
9532            pkg.applicationInfo.primaryCpuAbi = null;
9533            pkg.applicationInfo.secondaryCpuAbi = null;
9534        }
9535    }
9536
9537    private void killApplication(String pkgName, int appId, String reason) {
9538        // Request the ActivityManager to kill the process(only for existing packages)
9539        // so that we do not end up in a confused state while the user is still using the older
9540        // version of the application while the new one gets installed.
9541        final long token = Binder.clearCallingIdentity();
9542        try {
9543            IActivityManager am = ActivityManagerNative.getDefault();
9544            if (am != null) {
9545                try {
9546                    am.killApplicationWithAppId(pkgName, appId, reason);
9547                } catch (RemoteException e) {
9548                }
9549            }
9550        } finally {
9551            Binder.restoreCallingIdentity(token);
9552        }
9553    }
9554
9555    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9556        // Remove the parent package setting
9557        PackageSetting ps = (PackageSetting) pkg.mExtras;
9558        if (ps != null) {
9559            removePackageLI(ps, chatty);
9560        }
9561        // Remove the child package setting
9562        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9563        for (int i = 0; i < childCount; i++) {
9564            PackageParser.Package childPkg = pkg.childPackages.get(i);
9565            ps = (PackageSetting) childPkg.mExtras;
9566            if (ps != null) {
9567                removePackageLI(ps, chatty);
9568            }
9569        }
9570    }
9571
9572    void removePackageLI(PackageSetting ps, boolean chatty) {
9573        if (DEBUG_INSTALL) {
9574            if (chatty)
9575                Log.d(TAG, "Removing package " + ps.name);
9576        }
9577
9578        // writer
9579        synchronized (mPackages) {
9580            mPackages.remove(ps.name);
9581            final PackageParser.Package pkg = ps.pkg;
9582            if (pkg != null) {
9583                cleanPackageDataStructuresLILPw(pkg, chatty);
9584            }
9585        }
9586    }
9587
9588    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9589        if (DEBUG_INSTALL) {
9590            if (chatty)
9591                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9592        }
9593
9594        // writer
9595        synchronized (mPackages) {
9596            // Remove the parent package
9597            mPackages.remove(pkg.applicationInfo.packageName);
9598            cleanPackageDataStructuresLILPw(pkg, chatty);
9599
9600            // Remove the child packages
9601            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9602            for (int i = 0; i < childCount; i++) {
9603                PackageParser.Package childPkg = pkg.childPackages.get(i);
9604                mPackages.remove(childPkg.applicationInfo.packageName);
9605                cleanPackageDataStructuresLILPw(childPkg, chatty);
9606            }
9607        }
9608    }
9609
9610    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9611        int N = pkg.providers.size();
9612        StringBuilder r = null;
9613        int i;
9614        for (i=0; i<N; i++) {
9615            PackageParser.Provider p = pkg.providers.get(i);
9616            mProviders.removeProvider(p);
9617            if (p.info.authority == null) {
9618
9619                /* There was another ContentProvider with this authority when
9620                 * this app was installed so this authority is null,
9621                 * Ignore it as we don't have to unregister the provider.
9622                 */
9623                continue;
9624            }
9625            String names[] = p.info.authority.split(";");
9626            for (int j = 0; j < names.length; j++) {
9627                if (mProvidersByAuthority.get(names[j]) == p) {
9628                    mProvidersByAuthority.remove(names[j]);
9629                    if (DEBUG_REMOVE) {
9630                        if (chatty)
9631                            Log.d(TAG, "Unregistered content provider: " + names[j]
9632                                    + ", className = " + p.info.name + ", isSyncable = "
9633                                    + p.info.isSyncable);
9634                    }
9635                }
9636            }
9637            if (DEBUG_REMOVE && chatty) {
9638                if (r == null) {
9639                    r = new StringBuilder(256);
9640                } else {
9641                    r.append(' ');
9642                }
9643                r.append(p.info.name);
9644            }
9645        }
9646        if (r != null) {
9647            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9648        }
9649
9650        N = pkg.services.size();
9651        r = null;
9652        for (i=0; i<N; i++) {
9653            PackageParser.Service s = pkg.services.get(i);
9654            mServices.removeService(s);
9655            if (chatty) {
9656                if (r == null) {
9657                    r = new StringBuilder(256);
9658                } else {
9659                    r.append(' ');
9660                }
9661                r.append(s.info.name);
9662            }
9663        }
9664        if (r != null) {
9665            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9666        }
9667
9668        N = pkg.receivers.size();
9669        r = null;
9670        for (i=0; i<N; i++) {
9671            PackageParser.Activity a = pkg.receivers.get(i);
9672            mReceivers.removeActivity(a, "receiver");
9673            if (DEBUG_REMOVE && chatty) {
9674                if (r == null) {
9675                    r = new StringBuilder(256);
9676                } else {
9677                    r.append(' ');
9678                }
9679                r.append(a.info.name);
9680            }
9681        }
9682        if (r != null) {
9683            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9684        }
9685
9686        N = pkg.activities.size();
9687        r = null;
9688        for (i=0; i<N; i++) {
9689            PackageParser.Activity a = pkg.activities.get(i);
9690            mActivities.removeActivity(a, "activity");
9691            if (DEBUG_REMOVE && chatty) {
9692                if (r == null) {
9693                    r = new StringBuilder(256);
9694                } else {
9695                    r.append(' ');
9696                }
9697                r.append(a.info.name);
9698            }
9699        }
9700        if (r != null) {
9701            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9702        }
9703
9704        N = pkg.permissions.size();
9705        r = null;
9706        for (i=0; i<N; i++) {
9707            PackageParser.Permission p = pkg.permissions.get(i);
9708            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9709            if (bp == null) {
9710                bp = mSettings.mPermissionTrees.get(p.info.name);
9711            }
9712            if (bp != null && bp.perm == p) {
9713                bp.perm = null;
9714                if (DEBUG_REMOVE && chatty) {
9715                    if (r == null) {
9716                        r = new StringBuilder(256);
9717                    } else {
9718                        r.append(' ');
9719                    }
9720                    r.append(p.info.name);
9721                }
9722            }
9723            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9724                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9725                if (appOpPkgs != null) {
9726                    appOpPkgs.remove(pkg.packageName);
9727                }
9728            }
9729        }
9730        if (r != null) {
9731            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9732        }
9733
9734        N = pkg.requestedPermissions.size();
9735        r = null;
9736        for (i=0; i<N; i++) {
9737            String perm = pkg.requestedPermissions.get(i);
9738            BasePermission bp = mSettings.mPermissions.get(perm);
9739            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9740                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9741                if (appOpPkgs != null) {
9742                    appOpPkgs.remove(pkg.packageName);
9743                    if (appOpPkgs.isEmpty()) {
9744                        mAppOpPermissionPackages.remove(perm);
9745                    }
9746                }
9747            }
9748        }
9749        if (r != null) {
9750            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9751        }
9752
9753        N = pkg.instrumentation.size();
9754        r = null;
9755        for (i=0; i<N; i++) {
9756            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9757            mInstrumentation.remove(a.getComponentName());
9758            if (DEBUG_REMOVE && chatty) {
9759                if (r == null) {
9760                    r = new StringBuilder(256);
9761                } else {
9762                    r.append(' ');
9763                }
9764                r.append(a.info.name);
9765            }
9766        }
9767        if (r != null) {
9768            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9769        }
9770
9771        r = null;
9772        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9773            // Only system apps can hold shared libraries.
9774            if (pkg.libraryNames != null) {
9775                for (i=0; i<pkg.libraryNames.size(); i++) {
9776                    String name = pkg.libraryNames.get(i);
9777                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9778                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9779                        mSharedLibraries.remove(name);
9780                        if (DEBUG_REMOVE && chatty) {
9781                            if (r == null) {
9782                                r = new StringBuilder(256);
9783                            } else {
9784                                r.append(' ');
9785                            }
9786                            r.append(name);
9787                        }
9788                    }
9789                }
9790            }
9791        }
9792        if (r != null) {
9793            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9794        }
9795    }
9796
9797    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9798        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9799            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9800                return true;
9801            }
9802        }
9803        return false;
9804    }
9805
9806    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9807    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9808    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9809
9810    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9811        // Update the parent permissions
9812        updatePermissionsLPw(pkg.packageName, pkg, flags);
9813        // Update the child permissions
9814        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9815        for (int i = 0; i < childCount; i++) {
9816            PackageParser.Package childPkg = pkg.childPackages.get(i);
9817            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9818        }
9819    }
9820
9821    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9822            int flags) {
9823        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9824        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9825    }
9826
9827    private void updatePermissionsLPw(String changingPkg,
9828            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9829        // Make sure there are no dangling permission trees.
9830        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9831        while (it.hasNext()) {
9832            final BasePermission bp = it.next();
9833            if (bp.packageSetting == null) {
9834                // We may not yet have parsed the package, so just see if
9835                // we still know about its settings.
9836                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9837            }
9838            if (bp.packageSetting == null) {
9839                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9840                        + " from package " + bp.sourcePackage);
9841                it.remove();
9842            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9843                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9844                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9845                            + " from package " + bp.sourcePackage);
9846                    flags |= UPDATE_PERMISSIONS_ALL;
9847                    it.remove();
9848                }
9849            }
9850        }
9851
9852        // Make sure all dynamic permissions have been assigned to a package,
9853        // and make sure there are no dangling permissions.
9854        it = mSettings.mPermissions.values().iterator();
9855        while (it.hasNext()) {
9856            final BasePermission bp = it.next();
9857            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9858                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9859                        + bp.name + " pkg=" + bp.sourcePackage
9860                        + " info=" + bp.pendingInfo);
9861                if (bp.packageSetting == null && bp.pendingInfo != null) {
9862                    final BasePermission tree = findPermissionTreeLP(bp.name);
9863                    if (tree != null && tree.perm != null) {
9864                        bp.packageSetting = tree.packageSetting;
9865                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9866                                new PermissionInfo(bp.pendingInfo));
9867                        bp.perm.info.packageName = tree.perm.info.packageName;
9868                        bp.perm.info.name = bp.name;
9869                        bp.uid = tree.uid;
9870                    }
9871                }
9872            }
9873            if (bp.packageSetting == null) {
9874                // We may not yet have parsed the package, so just see if
9875                // we still know about its settings.
9876                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9877            }
9878            if (bp.packageSetting == null) {
9879                Slog.w(TAG, "Removing dangling permission: " + bp.name
9880                        + " from package " + bp.sourcePackage);
9881                it.remove();
9882            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9883                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9884                    Slog.i(TAG, "Removing old permission: " + bp.name
9885                            + " from package " + bp.sourcePackage);
9886                    flags |= UPDATE_PERMISSIONS_ALL;
9887                    it.remove();
9888                }
9889            }
9890        }
9891
9892        // Now update the permissions for all packages, in particular
9893        // replace the granted permissions of the system packages.
9894        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9895            for (PackageParser.Package pkg : mPackages.values()) {
9896                if (pkg != pkgInfo) {
9897                    // Only replace for packages on requested volume
9898                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9899                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9900                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9901                    grantPermissionsLPw(pkg, replace, changingPkg);
9902                }
9903            }
9904        }
9905
9906        if (pkgInfo != null) {
9907            // Only replace for packages on requested volume
9908            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9909            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9910                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9911            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9912        }
9913    }
9914
9915    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9916            String packageOfInterest) {
9917        // IMPORTANT: There are two types of permissions: install and runtime.
9918        // Install time permissions are granted when the app is installed to
9919        // all device users and users added in the future. Runtime permissions
9920        // are granted at runtime explicitly to specific users. Normal and signature
9921        // protected permissions are install time permissions. Dangerous permissions
9922        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9923        // otherwise they are runtime permissions. This function does not manage
9924        // runtime permissions except for the case an app targeting Lollipop MR1
9925        // being upgraded to target a newer SDK, in which case dangerous permissions
9926        // are transformed from install time to runtime ones.
9927
9928        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9929        if (ps == null) {
9930            return;
9931        }
9932
9933        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9934
9935        PermissionsState permissionsState = ps.getPermissionsState();
9936        PermissionsState origPermissions = permissionsState;
9937
9938        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9939
9940        boolean runtimePermissionsRevoked = false;
9941        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9942
9943        boolean changedInstallPermission = false;
9944
9945        if (replace) {
9946            ps.installPermissionsFixed = false;
9947            if (!ps.isSharedUser()) {
9948                origPermissions = new PermissionsState(permissionsState);
9949                permissionsState.reset();
9950            } else {
9951                // We need to know only about runtime permission changes since the
9952                // calling code always writes the install permissions state but
9953                // the runtime ones are written only if changed. The only cases of
9954                // changed runtime permissions here are promotion of an install to
9955                // runtime and revocation of a runtime from a shared user.
9956                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9957                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9958                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9959                    runtimePermissionsRevoked = true;
9960                }
9961            }
9962        }
9963
9964        permissionsState.setGlobalGids(mGlobalGids);
9965
9966        final int N = pkg.requestedPermissions.size();
9967        for (int i=0; i<N; i++) {
9968            final String name = pkg.requestedPermissions.get(i);
9969            final BasePermission bp = mSettings.mPermissions.get(name);
9970
9971            if (DEBUG_INSTALL) {
9972                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9973            }
9974
9975            if (bp == null || bp.packageSetting == null) {
9976                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9977                    Slog.w(TAG, "Unknown permission " + name
9978                            + " in package " + pkg.packageName);
9979                }
9980                continue;
9981            }
9982
9983            final String perm = bp.name;
9984            boolean allowedSig = false;
9985            int grant = GRANT_DENIED;
9986
9987            // Keep track of app op permissions.
9988            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9989                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9990                if (pkgs == null) {
9991                    pkgs = new ArraySet<>();
9992                    mAppOpPermissionPackages.put(bp.name, pkgs);
9993                }
9994                pkgs.add(pkg.packageName);
9995            }
9996
9997            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9998            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9999                    >= Build.VERSION_CODES.M;
10000            switch (level) {
10001                case PermissionInfo.PROTECTION_NORMAL: {
10002                    // For all apps normal permissions are install time ones.
10003                    grant = GRANT_INSTALL;
10004                } break;
10005
10006                case PermissionInfo.PROTECTION_DANGEROUS: {
10007                    // If a permission review is required for legacy apps we represent
10008                    // their permissions as always granted runtime ones since we need
10009                    // to keep the review required permission flag per user while an
10010                    // install permission's state is shared across all users.
10011                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
10012                        // For legacy apps dangerous permissions are install time ones.
10013                        grant = GRANT_INSTALL;
10014                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10015                        // For legacy apps that became modern, install becomes runtime.
10016                        grant = GRANT_UPGRADE;
10017                    } else if (mPromoteSystemApps
10018                            && isSystemApp(ps)
10019                            && mExistingSystemPackages.contains(ps.name)) {
10020                        // For legacy system apps, install becomes runtime.
10021                        // We cannot check hasInstallPermission() for system apps since those
10022                        // permissions were granted implicitly and not persisted pre-M.
10023                        grant = GRANT_UPGRADE;
10024                    } else {
10025                        // For modern apps keep runtime permissions unchanged.
10026                        grant = GRANT_RUNTIME;
10027                    }
10028                } break;
10029
10030                case PermissionInfo.PROTECTION_SIGNATURE: {
10031                    // For all apps signature permissions are install time ones.
10032                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10033                    if (allowedSig) {
10034                        grant = GRANT_INSTALL;
10035                    }
10036                } break;
10037            }
10038
10039            if (DEBUG_INSTALL) {
10040                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10041            }
10042
10043            if (grant != GRANT_DENIED) {
10044                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10045                    // If this is an existing, non-system package, then
10046                    // we can't add any new permissions to it.
10047                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10048                        // Except...  if this is a permission that was added
10049                        // to the platform (note: need to only do this when
10050                        // updating the platform).
10051                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10052                            grant = GRANT_DENIED;
10053                        }
10054                    }
10055                }
10056
10057                switch (grant) {
10058                    case GRANT_INSTALL: {
10059                        // Revoke this as runtime permission to handle the case of
10060                        // a runtime permission being downgraded to an install one.
10061                        // Also in permission review mode we keep dangerous permissions
10062                        // for legacy apps
10063                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10064                            if (origPermissions.getRuntimePermissionState(
10065                                    bp.name, userId) != null) {
10066                                // Revoke the runtime permission and clear the flags.
10067                                origPermissions.revokeRuntimePermission(bp, userId);
10068                                origPermissions.updatePermissionFlags(bp, userId,
10069                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10070                                // If we revoked a permission permission, we have to write.
10071                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10072                                        changedRuntimePermissionUserIds, userId);
10073                            }
10074                        }
10075                        // Grant an install permission.
10076                        if (permissionsState.grantInstallPermission(bp) !=
10077                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10078                            changedInstallPermission = true;
10079                        }
10080                    } break;
10081
10082                    case GRANT_RUNTIME: {
10083                        // Grant previously granted runtime permissions.
10084                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10085                            PermissionState permissionState = origPermissions
10086                                    .getRuntimePermissionState(bp.name, userId);
10087                            int flags = permissionState != null
10088                                    ? permissionState.getFlags() : 0;
10089                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10090                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10091                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10092                                    // If we cannot put the permission as it was, we have to write.
10093                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10094                                            changedRuntimePermissionUserIds, userId);
10095                                }
10096                                // If the app supports runtime permissions no need for a review.
10097                                if (Build.PERMISSIONS_REVIEW_REQUIRED
10098                                        && appSupportsRuntimePermissions
10099                                        && (flags & PackageManager
10100                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10101                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10102                                    // Since we changed the flags, we have to write.
10103                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10104                                            changedRuntimePermissionUserIds, userId);
10105                                }
10106                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
10107                                    && !appSupportsRuntimePermissions) {
10108                                // For legacy apps that need a permission review, every new
10109                                // runtime permission is granted but it is pending a review.
10110                                // We also need to review only platform defined runtime
10111                                // permissions as these are the only ones the platform knows
10112                                // how to disable the API to simulate revocation as legacy
10113                                // apps don't expect to run with revoked permissions.
10114                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10115                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10116                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10117                                        // We changed the flags, hence have to write.
10118                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10119                                                changedRuntimePermissionUserIds, userId);
10120                                    }
10121                                }
10122                                if (permissionsState.grantRuntimePermission(bp, userId)
10123                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10124                                    // We changed the permission, hence have to write.
10125                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10126                                            changedRuntimePermissionUserIds, userId);
10127                                }
10128                            }
10129                            // Propagate the permission flags.
10130                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10131                        }
10132                    } break;
10133
10134                    case GRANT_UPGRADE: {
10135                        // Grant runtime permissions for a previously held install permission.
10136                        PermissionState permissionState = origPermissions
10137                                .getInstallPermissionState(bp.name);
10138                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10139
10140                        if (origPermissions.revokeInstallPermission(bp)
10141                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10142                            // We will be transferring the permission flags, so clear them.
10143                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10144                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10145                            changedInstallPermission = true;
10146                        }
10147
10148                        // If the permission is not to be promoted to runtime we ignore it and
10149                        // also its other flags as they are not applicable to install permissions.
10150                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10151                            for (int userId : currentUserIds) {
10152                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10153                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10154                                    // Transfer the permission flags.
10155                                    permissionsState.updatePermissionFlags(bp, userId,
10156                                            flags, flags);
10157                                    // If we granted the permission, we have to write.
10158                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10159                                            changedRuntimePermissionUserIds, userId);
10160                                }
10161                            }
10162                        }
10163                    } break;
10164
10165                    default: {
10166                        if (packageOfInterest == null
10167                                || packageOfInterest.equals(pkg.packageName)) {
10168                            Slog.w(TAG, "Not granting permission " + perm
10169                                    + " to package " + pkg.packageName
10170                                    + " because it was previously installed without");
10171                        }
10172                    } break;
10173                }
10174            } else {
10175                if (permissionsState.revokeInstallPermission(bp) !=
10176                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10177                    // Also drop the permission flags.
10178                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10179                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10180                    changedInstallPermission = true;
10181                    Slog.i(TAG, "Un-granting permission " + perm
10182                            + " from package " + pkg.packageName
10183                            + " (protectionLevel=" + bp.protectionLevel
10184                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10185                            + ")");
10186                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10187                    // Don't print warning for app op permissions, since it is fine for them
10188                    // not to be granted, there is a UI for the user to decide.
10189                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10190                        Slog.w(TAG, "Not granting permission " + perm
10191                                + " to package " + pkg.packageName
10192                                + " (protectionLevel=" + bp.protectionLevel
10193                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10194                                + ")");
10195                    }
10196                }
10197            }
10198        }
10199
10200        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10201                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10202            // This is the first that we have heard about this package, so the
10203            // permissions we have now selected are fixed until explicitly
10204            // changed.
10205            ps.installPermissionsFixed = true;
10206        }
10207
10208        // Persist the runtime permissions state for users with changes. If permissions
10209        // were revoked because no app in the shared user declares them we have to
10210        // write synchronously to avoid losing runtime permissions state.
10211        for (int userId : changedRuntimePermissionUserIds) {
10212            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10213        }
10214
10215        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10216    }
10217
10218    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10219        boolean allowed = false;
10220        final int NP = PackageParser.NEW_PERMISSIONS.length;
10221        for (int ip=0; ip<NP; ip++) {
10222            final PackageParser.NewPermissionInfo npi
10223                    = PackageParser.NEW_PERMISSIONS[ip];
10224            if (npi.name.equals(perm)
10225                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10226                allowed = true;
10227                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10228                        + pkg.packageName);
10229                break;
10230            }
10231        }
10232        return allowed;
10233    }
10234
10235    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10236            BasePermission bp, PermissionsState origPermissions) {
10237        boolean allowed;
10238        allowed = (compareSignatures(
10239                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10240                        == PackageManager.SIGNATURE_MATCH)
10241                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10242                        == PackageManager.SIGNATURE_MATCH);
10243        if (!allowed && (bp.protectionLevel
10244                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10245            if (isSystemApp(pkg)) {
10246                // For updated system applications, a system permission
10247                // is granted only if it had been defined by the original application.
10248                if (pkg.isUpdatedSystemApp()) {
10249                    final PackageSetting sysPs = mSettings
10250                            .getDisabledSystemPkgLPr(pkg.packageName);
10251                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10252                        // If the original was granted this permission, we take
10253                        // that grant decision as read and propagate it to the
10254                        // update.
10255                        if (sysPs.isPrivileged()) {
10256                            allowed = true;
10257                        }
10258                    } else {
10259                        // The system apk may have been updated with an older
10260                        // version of the one on the data partition, but which
10261                        // granted a new system permission that it didn't have
10262                        // before.  In this case we do want to allow the app to
10263                        // now get the new permission if the ancestral apk is
10264                        // privileged to get it.
10265                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10266                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10267                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10268                                    allowed = true;
10269                                    break;
10270                                }
10271                            }
10272                        }
10273                        // Also if a privileged parent package on the system image or any of
10274                        // its children requested a privileged permission, the updated child
10275                        // packages can also get the permission.
10276                        if (pkg.parentPackage != null) {
10277                            final PackageSetting disabledSysParentPs = mSettings
10278                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10279                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10280                                    && disabledSysParentPs.isPrivileged()) {
10281                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10282                                    allowed = true;
10283                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10284                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10285                                    for (int i = 0; i < count; i++) {
10286                                        PackageParser.Package disabledSysChildPkg =
10287                                                disabledSysParentPs.pkg.childPackages.get(i);
10288                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10289                                                perm)) {
10290                                            allowed = true;
10291                                            break;
10292                                        }
10293                                    }
10294                                }
10295                            }
10296                        }
10297                    }
10298                } else {
10299                    allowed = isPrivilegedApp(pkg);
10300                }
10301            }
10302        }
10303        if (!allowed) {
10304            if (!allowed && (bp.protectionLevel
10305                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10306                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10307                // If this was a previously normal/dangerous permission that got moved
10308                // to a system permission as part of the runtime permission redesign, then
10309                // we still want to blindly grant it to old apps.
10310                allowed = true;
10311            }
10312            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10313                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10314                // If this permission is to be granted to the system installer and
10315                // this app is an installer, then it gets the permission.
10316                allowed = true;
10317            }
10318            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10319                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10320                // If this permission is to be granted to the system verifier and
10321                // this app is a verifier, then it gets the permission.
10322                allowed = true;
10323            }
10324            if (!allowed && (bp.protectionLevel
10325                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10326                    && isSystemApp(pkg)) {
10327                // Any pre-installed system app is allowed to get this permission.
10328                allowed = true;
10329            }
10330            if (!allowed && (bp.protectionLevel
10331                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10332                // For development permissions, a development permission
10333                // is granted only if it was already granted.
10334                allowed = origPermissions.hasInstallPermission(perm);
10335            }
10336            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10337                    && pkg.packageName.equals(mSetupWizardPackage)) {
10338                // If this permission is to be granted to the system setup wizard and
10339                // this app is a setup wizard, then it gets the permission.
10340                allowed = true;
10341            }
10342        }
10343        return allowed;
10344    }
10345
10346    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10347        final int permCount = pkg.requestedPermissions.size();
10348        for (int j = 0; j < permCount; j++) {
10349            String requestedPermission = pkg.requestedPermissions.get(j);
10350            if (permission.equals(requestedPermission)) {
10351                return true;
10352            }
10353        }
10354        return false;
10355    }
10356
10357    final class ActivityIntentResolver
10358            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10359        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10360                boolean defaultOnly, int userId) {
10361            if (!sUserManager.exists(userId)) return null;
10362            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10363            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10364        }
10365
10366        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10367                int userId) {
10368            if (!sUserManager.exists(userId)) return null;
10369            mFlags = flags;
10370            return super.queryIntent(intent, resolvedType,
10371                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10372        }
10373
10374        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10375                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10376            if (!sUserManager.exists(userId)) return null;
10377            if (packageActivities == null) {
10378                return null;
10379            }
10380            mFlags = flags;
10381            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10382            final int N = packageActivities.size();
10383            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10384                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10385
10386            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10387            for (int i = 0; i < N; ++i) {
10388                intentFilters = packageActivities.get(i).intents;
10389                if (intentFilters != null && intentFilters.size() > 0) {
10390                    PackageParser.ActivityIntentInfo[] array =
10391                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10392                    intentFilters.toArray(array);
10393                    listCut.add(array);
10394                }
10395            }
10396            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10397        }
10398
10399        /**
10400         * Finds a privileged activity that matches the specified activity names.
10401         */
10402        private PackageParser.Activity findMatchingActivity(
10403                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10404            for (PackageParser.Activity sysActivity : activityList) {
10405                if (sysActivity.info.name.equals(activityInfo.name)) {
10406                    return sysActivity;
10407                }
10408                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10409                    return sysActivity;
10410                }
10411                if (sysActivity.info.targetActivity != null) {
10412                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10413                        return sysActivity;
10414                    }
10415                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10416                        return sysActivity;
10417                    }
10418                }
10419            }
10420            return null;
10421        }
10422
10423        public class IterGenerator<E> {
10424            public Iterator<E> generate(ActivityIntentInfo info) {
10425                return null;
10426            }
10427        }
10428
10429        public class ActionIterGenerator extends IterGenerator<String> {
10430            @Override
10431            public Iterator<String> generate(ActivityIntentInfo info) {
10432                return info.actionsIterator();
10433            }
10434        }
10435
10436        public class CategoriesIterGenerator extends IterGenerator<String> {
10437            @Override
10438            public Iterator<String> generate(ActivityIntentInfo info) {
10439                return info.categoriesIterator();
10440            }
10441        }
10442
10443        public class SchemesIterGenerator extends IterGenerator<String> {
10444            @Override
10445            public Iterator<String> generate(ActivityIntentInfo info) {
10446                return info.schemesIterator();
10447            }
10448        }
10449
10450        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10451            @Override
10452            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10453                return info.authoritiesIterator();
10454            }
10455        }
10456
10457        /**
10458         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10459         * MODIFIED. Do not pass in a list that should not be changed.
10460         */
10461        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10462                IterGenerator<T> generator, Iterator<T> searchIterator) {
10463            // loop through the set of actions; every one must be found in the intent filter
10464            while (searchIterator.hasNext()) {
10465                // we must have at least one filter in the list to consider a match
10466                if (intentList.size() == 0) {
10467                    break;
10468                }
10469
10470                final T searchAction = searchIterator.next();
10471
10472                // loop through the set of intent filters
10473                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10474                while (intentIter.hasNext()) {
10475                    final ActivityIntentInfo intentInfo = intentIter.next();
10476                    boolean selectionFound = false;
10477
10478                    // loop through the intent filter's selection criteria; at least one
10479                    // of them must match the searched criteria
10480                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10481                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10482                        final T intentSelection = intentSelectionIter.next();
10483                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10484                            selectionFound = true;
10485                            break;
10486                        }
10487                    }
10488
10489                    // the selection criteria wasn't found in this filter's set; this filter
10490                    // is not a potential match
10491                    if (!selectionFound) {
10492                        intentIter.remove();
10493                    }
10494                }
10495            }
10496        }
10497
10498        private boolean isProtectedAction(ActivityIntentInfo filter) {
10499            final Iterator<String> actionsIter = filter.actionsIterator();
10500            while (actionsIter != null && actionsIter.hasNext()) {
10501                final String filterAction = actionsIter.next();
10502                if (PROTECTED_ACTIONS.contains(filterAction)) {
10503                    return true;
10504                }
10505            }
10506            return false;
10507        }
10508
10509        /**
10510         * Adjusts the priority of the given intent filter according to policy.
10511         * <p>
10512         * <ul>
10513         * <li>The priority for non privileged applications is capped to '0'</li>
10514         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10515         * <li>The priority for unbundled updates to privileged applications is capped to the
10516         *      priority defined on the system partition</li>
10517         * </ul>
10518         * <p>
10519         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10520         * allowed to obtain any priority on any action.
10521         */
10522        private void adjustPriority(
10523                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10524            // nothing to do; priority is fine as-is
10525            if (intent.getPriority() <= 0) {
10526                return;
10527            }
10528
10529            final ActivityInfo activityInfo = intent.activity.info;
10530            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10531
10532            final boolean privilegedApp =
10533                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10534            if (!privilegedApp) {
10535                // non-privileged applications can never define a priority >0
10536                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10537                        + " package: " + applicationInfo.packageName
10538                        + " activity: " + intent.activity.className
10539                        + " origPrio: " + intent.getPriority());
10540                intent.setPriority(0);
10541                return;
10542            }
10543
10544            if (systemActivities == null) {
10545                // the system package is not disabled; we're parsing the system partition
10546                if (isProtectedAction(intent)) {
10547                    if (mDeferProtectedFilters) {
10548                        // We can't deal with these just yet. No component should ever obtain a
10549                        // >0 priority for a protected actions, with ONE exception -- the setup
10550                        // wizard. The setup wizard, however, cannot be known until we're able to
10551                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10552                        // until all intent filters have been processed. Chicken, meet egg.
10553                        // Let the filter temporarily have a high priority and rectify the
10554                        // priorities after all system packages have been scanned.
10555                        mProtectedFilters.add(intent);
10556                        if (DEBUG_FILTERS) {
10557                            Slog.i(TAG, "Protected action; save for later;"
10558                                    + " package: " + applicationInfo.packageName
10559                                    + " activity: " + intent.activity.className
10560                                    + " origPrio: " + intent.getPriority());
10561                        }
10562                        return;
10563                    } else {
10564                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10565                            Slog.i(TAG, "No setup wizard;"
10566                                + " All protected intents capped to priority 0");
10567                        }
10568                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10569                            if (DEBUG_FILTERS) {
10570                                Slog.i(TAG, "Found setup wizard;"
10571                                    + " allow priority " + intent.getPriority() + ";"
10572                                    + " package: " + intent.activity.info.packageName
10573                                    + " activity: " + intent.activity.className
10574                                    + " priority: " + intent.getPriority());
10575                            }
10576                            // setup wizard gets whatever it wants
10577                            return;
10578                        }
10579                        Slog.w(TAG, "Protected action; cap priority to 0;"
10580                                + " package: " + intent.activity.info.packageName
10581                                + " activity: " + intent.activity.className
10582                                + " origPrio: " + intent.getPriority());
10583                        intent.setPriority(0);
10584                        return;
10585                    }
10586                }
10587                // privileged apps on the system image get whatever priority they request
10588                return;
10589            }
10590
10591            // privileged app unbundled update ... try to find the same activity
10592            final PackageParser.Activity foundActivity =
10593                    findMatchingActivity(systemActivities, activityInfo);
10594            if (foundActivity == null) {
10595                // this is a new activity; it cannot obtain >0 priority
10596                if (DEBUG_FILTERS) {
10597                    Slog.i(TAG, "New activity; cap priority to 0;"
10598                            + " package: " + applicationInfo.packageName
10599                            + " activity: " + intent.activity.className
10600                            + " origPrio: " + intent.getPriority());
10601                }
10602                intent.setPriority(0);
10603                return;
10604            }
10605
10606            // found activity, now check for filter equivalence
10607
10608            // a shallow copy is enough; we modify the list, not its contents
10609            final List<ActivityIntentInfo> intentListCopy =
10610                    new ArrayList<>(foundActivity.intents);
10611            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10612
10613            // find matching action subsets
10614            final Iterator<String> actionsIterator = intent.actionsIterator();
10615            if (actionsIterator != null) {
10616                getIntentListSubset(
10617                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10618                if (intentListCopy.size() == 0) {
10619                    // no more intents to match; we're not equivalent
10620                    if (DEBUG_FILTERS) {
10621                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10622                                + " package: " + applicationInfo.packageName
10623                                + " activity: " + intent.activity.className
10624                                + " origPrio: " + intent.getPriority());
10625                    }
10626                    intent.setPriority(0);
10627                    return;
10628                }
10629            }
10630
10631            // find matching category subsets
10632            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10633            if (categoriesIterator != null) {
10634                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10635                        categoriesIterator);
10636                if (intentListCopy.size() == 0) {
10637                    // no more intents to match; we're not equivalent
10638                    if (DEBUG_FILTERS) {
10639                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10640                                + " package: " + applicationInfo.packageName
10641                                + " activity: " + intent.activity.className
10642                                + " origPrio: " + intent.getPriority());
10643                    }
10644                    intent.setPriority(0);
10645                    return;
10646                }
10647            }
10648
10649            // find matching schemes subsets
10650            final Iterator<String> schemesIterator = intent.schemesIterator();
10651            if (schemesIterator != null) {
10652                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10653                        schemesIterator);
10654                if (intentListCopy.size() == 0) {
10655                    // no more intents to match; we're not equivalent
10656                    if (DEBUG_FILTERS) {
10657                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10658                                + " package: " + applicationInfo.packageName
10659                                + " activity: " + intent.activity.className
10660                                + " origPrio: " + intent.getPriority());
10661                    }
10662                    intent.setPriority(0);
10663                    return;
10664                }
10665            }
10666
10667            // find matching authorities subsets
10668            final Iterator<IntentFilter.AuthorityEntry>
10669                    authoritiesIterator = intent.authoritiesIterator();
10670            if (authoritiesIterator != null) {
10671                getIntentListSubset(intentListCopy,
10672                        new AuthoritiesIterGenerator(),
10673                        authoritiesIterator);
10674                if (intentListCopy.size() == 0) {
10675                    // no more intents to match; we're not equivalent
10676                    if (DEBUG_FILTERS) {
10677                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10678                                + " package: " + applicationInfo.packageName
10679                                + " activity: " + intent.activity.className
10680                                + " origPrio: " + intent.getPriority());
10681                    }
10682                    intent.setPriority(0);
10683                    return;
10684                }
10685            }
10686
10687            // we found matching filter(s); app gets the max priority of all intents
10688            int cappedPriority = 0;
10689            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10690                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10691            }
10692            if (intent.getPriority() > cappedPriority) {
10693                if (DEBUG_FILTERS) {
10694                    Slog.i(TAG, "Found matching filter(s);"
10695                            + " cap priority to " + cappedPriority + ";"
10696                            + " package: " + applicationInfo.packageName
10697                            + " activity: " + intent.activity.className
10698                            + " origPrio: " + intent.getPriority());
10699                }
10700                intent.setPriority(cappedPriority);
10701                return;
10702            }
10703            // all this for nothing; the requested priority was <= what was on the system
10704        }
10705
10706        public final void addActivity(PackageParser.Activity a, String type) {
10707            mActivities.put(a.getComponentName(), a);
10708            if (DEBUG_SHOW_INFO)
10709                Log.v(
10710                TAG, "  " + type + " " +
10711                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10712            if (DEBUG_SHOW_INFO)
10713                Log.v(TAG, "    Class=" + a.info.name);
10714            final int NI = a.intents.size();
10715            for (int j=0; j<NI; j++) {
10716                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10717                if ("activity".equals(type)) {
10718                    final PackageSetting ps =
10719                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10720                    final List<PackageParser.Activity> systemActivities =
10721                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10722                    adjustPriority(systemActivities, intent);
10723                }
10724                if (DEBUG_SHOW_INFO) {
10725                    Log.v(TAG, "    IntentFilter:");
10726                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10727                }
10728                if (!intent.debugCheck()) {
10729                    Log.w(TAG, "==> For Activity " + a.info.name);
10730                }
10731                addFilter(intent);
10732            }
10733        }
10734
10735        public final void removeActivity(PackageParser.Activity a, String type) {
10736            mActivities.remove(a.getComponentName());
10737            if (DEBUG_SHOW_INFO) {
10738                Log.v(TAG, "  " + type + " "
10739                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10740                                : a.info.name) + ":");
10741                Log.v(TAG, "    Class=" + a.info.name);
10742            }
10743            final int NI = a.intents.size();
10744            for (int j=0; j<NI; j++) {
10745                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10746                if (DEBUG_SHOW_INFO) {
10747                    Log.v(TAG, "    IntentFilter:");
10748                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10749                }
10750                removeFilter(intent);
10751            }
10752        }
10753
10754        @Override
10755        protected boolean allowFilterResult(
10756                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10757            ActivityInfo filterAi = filter.activity.info;
10758            for (int i=dest.size()-1; i>=0; i--) {
10759                ActivityInfo destAi = dest.get(i).activityInfo;
10760                if (destAi.name == filterAi.name
10761                        && destAi.packageName == filterAi.packageName) {
10762                    return false;
10763                }
10764            }
10765            return true;
10766        }
10767
10768        @Override
10769        protected ActivityIntentInfo[] newArray(int size) {
10770            return new ActivityIntentInfo[size];
10771        }
10772
10773        @Override
10774        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10775            if (!sUserManager.exists(userId)) return true;
10776            PackageParser.Package p = filter.activity.owner;
10777            if (p != null) {
10778                PackageSetting ps = (PackageSetting)p.mExtras;
10779                if (ps != null) {
10780                    // System apps are never considered stopped for purposes of
10781                    // filtering, because there may be no way for the user to
10782                    // actually re-launch them.
10783                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10784                            && ps.getStopped(userId);
10785                }
10786            }
10787            return false;
10788        }
10789
10790        @Override
10791        protected boolean isPackageForFilter(String packageName,
10792                PackageParser.ActivityIntentInfo info) {
10793            return packageName.equals(info.activity.owner.packageName);
10794        }
10795
10796        @Override
10797        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10798                int match, int userId) {
10799            if (!sUserManager.exists(userId)) return null;
10800            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10801                return null;
10802            }
10803            final PackageParser.Activity activity = info.activity;
10804            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10805            if (ps == null) {
10806                return null;
10807            }
10808            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10809                    ps.readUserState(userId), userId);
10810            if (ai == null) {
10811                return null;
10812            }
10813            final ResolveInfo res = new ResolveInfo();
10814            res.activityInfo = ai;
10815            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10816                res.filter = info;
10817            }
10818            if (info != null) {
10819                res.handleAllWebDataURI = info.handleAllWebDataURI();
10820            }
10821            res.priority = info.getPriority();
10822            res.preferredOrder = activity.owner.mPreferredOrder;
10823            //System.out.println("Result: " + res.activityInfo.className +
10824            //                   " = " + res.priority);
10825            res.match = match;
10826            res.isDefault = info.hasDefault;
10827            res.labelRes = info.labelRes;
10828            res.nonLocalizedLabel = info.nonLocalizedLabel;
10829            if (userNeedsBadging(userId)) {
10830                res.noResourceId = true;
10831            } else {
10832                res.icon = info.icon;
10833            }
10834            res.iconResourceId = info.icon;
10835            res.system = res.activityInfo.applicationInfo.isSystemApp();
10836            return res;
10837        }
10838
10839        @Override
10840        protected void sortResults(List<ResolveInfo> results) {
10841            Collections.sort(results, mResolvePrioritySorter);
10842        }
10843
10844        @Override
10845        protected void dumpFilter(PrintWriter out, String prefix,
10846                PackageParser.ActivityIntentInfo filter) {
10847            out.print(prefix); out.print(
10848                    Integer.toHexString(System.identityHashCode(filter.activity)));
10849                    out.print(' ');
10850                    filter.activity.printComponentShortName(out);
10851                    out.print(" filter ");
10852                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10853        }
10854
10855        @Override
10856        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10857            return filter.activity;
10858        }
10859
10860        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10861            PackageParser.Activity activity = (PackageParser.Activity)label;
10862            out.print(prefix); out.print(
10863                    Integer.toHexString(System.identityHashCode(activity)));
10864                    out.print(' ');
10865                    activity.printComponentShortName(out);
10866            if (count > 1) {
10867                out.print(" ("); out.print(count); out.print(" filters)");
10868            }
10869            out.println();
10870        }
10871
10872        // Keys are String (activity class name), values are Activity.
10873        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10874                = new ArrayMap<ComponentName, PackageParser.Activity>();
10875        private int mFlags;
10876    }
10877
10878    private final class ServiceIntentResolver
10879            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10880        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10881                boolean defaultOnly, int userId) {
10882            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10883            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10884        }
10885
10886        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10887                int userId) {
10888            if (!sUserManager.exists(userId)) return null;
10889            mFlags = flags;
10890            return super.queryIntent(intent, resolvedType,
10891                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10892        }
10893
10894        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10895                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10896            if (!sUserManager.exists(userId)) return null;
10897            if (packageServices == null) {
10898                return null;
10899            }
10900            mFlags = flags;
10901            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10902            final int N = packageServices.size();
10903            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10904                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10905
10906            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10907            for (int i = 0; i < N; ++i) {
10908                intentFilters = packageServices.get(i).intents;
10909                if (intentFilters != null && intentFilters.size() > 0) {
10910                    PackageParser.ServiceIntentInfo[] array =
10911                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10912                    intentFilters.toArray(array);
10913                    listCut.add(array);
10914                }
10915            }
10916            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10917        }
10918
10919        public final void addService(PackageParser.Service s) {
10920            mServices.put(s.getComponentName(), s);
10921            if (DEBUG_SHOW_INFO) {
10922                Log.v(TAG, "  "
10923                        + (s.info.nonLocalizedLabel != null
10924                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10925                Log.v(TAG, "    Class=" + s.info.name);
10926            }
10927            final int NI = s.intents.size();
10928            int j;
10929            for (j=0; j<NI; j++) {
10930                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10931                if (DEBUG_SHOW_INFO) {
10932                    Log.v(TAG, "    IntentFilter:");
10933                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10934                }
10935                if (!intent.debugCheck()) {
10936                    Log.w(TAG, "==> For Service " + s.info.name);
10937                }
10938                addFilter(intent);
10939            }
10940        }
10941
10942        public final void removeService(PackageParser.Service s) {
10943            mServices.remove(s.getComponentName());
10944            if (DEBUG_SHOW_INFO) {
10945                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10946                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10947                Log.v(TAG, "    Class=" + s.info.name);
10948            }
10949            final int NI = s.intents.size();
10950            int j;
10951            for (j=0; j<NI; j++) {
10952                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10953                if (DEBUG_SHOW_INFO) {
10954                    Log.v(TAG, "    IntentFilter:");
10955                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10956                }
10957                removeFilter(intent);
10958            }
10959        }
10960
10961        @Override
10962        protected boolean allowFilterResult(
10963                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10964            ServiceInfo filterSi = filter.service.info;
10965            for (int i=dest.size()-1; i>=0; i--) {
10966                ServiceInfo destAi = dest.get(i).serviceInfo;
10967                if (destAi.name == filterSi.name
10968                        && destAi.packageName == filterSi.packageName) {
10969                    return false;
10970                }
10971            }
10972            return true;
10973        }
10974
10975        @Override
10976        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10977            return new PackageParser.ServiceIntentInfo[size];
10978        }
10979
10980        @Override
10981        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10982            if (!sUserManager.exists(userId)) return true;
10983            PackageParser.Package p = filter.service.owner;
10984            if (p != null) {
10985                PackageSetting ps = (PackageSetting)p.mExtras;
10986                if (ps != null) {
10987                    // System apps are never considered stopped for purposes of
10988                    // filtering, because there may be no way for the user to
10989                    // actually re-launch them.
10990                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10991                            && ps.getStopped(userId);
10992                }
10993            }
10994            return false;
10995        }
10996
10997        @Override
10998        protected boolean isPackageForFilter(String packageName,
10999                PackageParser.ServiceIntentInfo info) {
11000            return packageName.equals(info.service.owner.packageName);
11001        }
11002
11003        @Override
11004        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11005                int match, int userId) {
11006            if (!sUserManager.exists(userId)) return null;
11007            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11008            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11009                return null;
11010            }
11011            final PackageParser.Service service = info.service;
11012            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11013            if (ps == null) {
11014                return null;
11015            }
11016            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11017                    ps.readUserState(userId), userId);
11018            if (si == null) {
11019                return null;
11020            }
11021            final ResolveInfo res = new ResolveInfo();
11022            res.serviceInfo = si;
11023            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11024                res.filter = filter;
11025            }
11026            res.priority = info.getPriority();
11027            res.preferredOrder = service.owner.mPreferredOrder;
11028            res.match = match;
11029            res.isDefault = info.hasDefault;
11030            res.labelRes = info.labelRes;
11031            res.nonLocalizedLabel = info.nonLocalizedLabel;
11032            res.icon = info.icon;
11033            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11034            return res;
11035        }
11036
11037        @Override
11038        protected void sortResults(List<ResolveInfo> results) {
11039            Collections.sort(results, mResolvePrioritySorter);
11040        }
11041
11042        @Override
11043        protected void dumpFilter(PrintWriter out, String prefix,
11044                PackageParser.ServiceIntentInfo filter) {
11045            out.print(prefix); out.print(
11046                    Integer.toHexString(System.identityHashCode(filter.service)));
11047                    out.print(' ');
11048                    filter.service.printComponentShortName(out);
11049                    out.print(" filter ");
11050                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11051        }
11052
11053        @Override
11054        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11055            return filter.service;
11056        }
11057
11058        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11059            PackageParser.Service service = (PackageParser.Service)label;
11060            out.print(prefix); out.print(
11061                    Integer.toHexString(System.identityHashCode(service)));
11062                    out.print(' ');
11063                    service.printComponentShortName(out);
11064            if (count > 1) {
11065                out.print(" ("); out.print(count); out.print(" filters)");
11066            }
11067            out.println();
11068        }
11069
11070//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11071//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11072//            final List<ResolveInfo> retList = Lists.newArrayList();
11073//            while (i.hasNext()) {
11074//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11075//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11076//                    retList.add(resolveInfo);
11077//                }
11078//            }
11079//            return retList;
11080//        }
11081
11082        // Keys are String (activity class name), values are Activity.
11083        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11084                = new ArrayMap<ComponentName, PackageParser.Service>();
11085        private int mFlags;
11086    };
11087
11088    private final class ProviderIntentResolver
11089            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11090        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11091                boolean defaultOnly, int userId) {
11092            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11093            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11094        }
11095
11096        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11097                int userId) {
11098            if (!sUserManager.exists(userId))
11099                return null;
11100            mFlags = flags;
11101            return super.queryIntent(intent, resolvedType,
11102                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11103        }
11104
11105        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11106                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11107            if (!sUserManager.exists(userId))
11108                return null;
11109            if (packageProviders == null) {
11110                return null;
11111            }
11112            mFlags = flags;
11113            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11114            final int N = packageProviders.size();
11115            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11116                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11117
11118            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11119            for (int i = 0; i < N; ++i) {
11120                intentFilters = packageProviders.get(i).intents;
11121                if (intentFilters != null && intentFilters.size() > 0) {
11122                    PackageParser.ProviderIntentInfo[] array =
11123                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11124                    intentFilters.toArray(array);
11125                    listCut.add(array);
11126                }
11127            }
11128            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11129        }
11130
11131        public final void addProvider(PackageParser.Provider p) {
11132            if (mProviders.containsKey(p.getComponentName())) {
11133                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11134                return;
11135            }
11136
11137            mProviders.put(p.getComponentName(), p);
11138            if (DEBUG_SHOW_INFO) {
11139                Log.v(TAG, "  "
11140                        + (p.info.nonLocalizedLabel != null
11141                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11142                Log.v(TAG, "    Class=" + p.info.name);
11143            }
11144            final int NI = p.intents.size();
11145            int j;
11146            for (j = 0; j < NI; j++) {
11147                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11148                if (DEBUG_SHOW_INFO) {
11149                    Log.v(TAG, "    IntentFilter:");
11150                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11151                }
11152                if (!intent.debugCheck()) {
11153                    Log.w(TAG, "==> For Provider " + p.info.name);
11154                }
11155                addFilter(intent);
11156            }
11157        }
11158
11159        public final void removeProvider(PackageParser.Provider p) {
11160            mProviders.remove(p.getComponentName());
11161            if (DEBUG_SHOW_INFO) {
11162                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11163                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11164                Log.v(TAG, "    Class=" + p.info.name);
11165            }
11166            final int NI = p.intents.size();
11167            int j;
11168            for (j = 0; j < NI; j++) {
11169                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11170                if (DEBUG_SHOW_INFO) {
11171                    Log.v(TAG, "    IntentFilter:");
11172                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11173                }
11174                removeFilter(intent);
11175            }
11176        }
11177
11178        @Override
11179        protected boolean allowFilterResult(
11180                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11181            ProviderInfo filterPi = filter.provider.info;
11182            for (int i = dest.size() - 1; i >= 0; i--) {
11183                ProviderInfo destPi = dest.get(i).providerInfo;
11184                if (destPi.name == filterPi.name
11185                        && destPi.packageName == filterPi.packageName) {
11186                    return false;
11187                }
11188            }
11189            return true;
11190        }
11191
11192        @Override
11193        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11194            return new PackageParser.ProviderIntentInfo[size];
11195        }
11196
11197        @Override
11198        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11199            if (!sUserManager.exists(userId))
11200                return true;
11201            PackageParser.Package p = filter.provider.owner;
11202            if (p != null) {
11203                PackageSetting ps = (PackageSetting) p.mExtras;
11204                if (ps != null) {
11205                    // System apps are never considered stopped for purposes of
11206                    // filtering, because there may be no way for the user to
11207                    // actually re-launch them.
11208                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11209                            && ps.getStopped(userId);
11210                }
11211            }
11212            return false;
11213        }
11214
11215        @Override
11216        protected boolean isPackageForFilter(String packageName,
11217                PackageParser.ProviderIntentInfo info) {
11218            return packageName.equals(info.provider.owner.packageName);
11219        }
11220
11221        @Override
11222        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11223                int match, int userId) {
11224            if (!sUserManager.exists(userId))
11225                return null;
11226            final PackageParser.ProviderIntentInfo info = filter;
11227            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11228                return null;
11229            }
11230            final PackageParser.Provider provider = info.provider;
11231            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11232            if (ps == null) {
11233                return null;
11234            }
11235            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11236                    ps.readUserState(userId), userId);
11237            if (pi == null) {
11238                return null;
11239            }
11240            final ResolveInfo res = new ResolveInfo();
11241            res.providerInfo = pi;
11242            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11243                res.filter = filter;
11244            }
11245            res.priority = info.getPriority();
11246            res.preferredOrder = provider.owner.mPreferredOrder;
11247            res.match = match;
11248            res.isDefault = info.hasDefault;
11249            res.labelRes = info.labelRes;
11250            res.nonLocalizedLabel = info.nonLocalizedLabel;
11251            res.icon = info.icon;
11252            res.system = res.providerInfo.applicationInfo.isSystemApp();
11253            return res;
11254        }
11255
11256        @Override
11257        protected void sortResults(List<ResolveInfo> results) {
11258            Collections.sort(results, mResolvePrioritySorter);
11259        }
11260
11261        @Override
11262        protected void dumpFilter(PrintWriter out, String prefix,
11263                PackageParser.ProviderIntentInfo filter) {
11264            out.print(prefix);
11265            out.print(
11266                    Integer.toHexString(System.identityHashCode(filter.provider)));
11267            out.print(' ');
11268            filter.provider.printComponentShortName(out);
11269            out.print(" filter ");
11270            out.println(Integer.toHexString(System.identityHashCode(filter)));
11271        }
11272
11273        @Override
11274        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11275            return filter.provider;
11276        }
11277
11278        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11279            PackageParser.Provider provider = (PackageParser.Provider)label;
11280            out.print(prefix); out.print(
11281                    Integer.toHexString(System.identityHashCode(provider)));
11282                    out.print(' ');
11283                    provider.printComponentShortName(out);
11284            if (count > 1) {
11285                out.print(" ("); out.print(count); out.print(" filters)");
11286            }
11287            out.println();
11288        }
11289
11290        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11291                = new ArrayMap<ComponentName, PackageParser.Provider>();
11292        private int mFlags;
11293    }
11294
11295    private static final class EphemeralIntentResolver
11296            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11297        @Override
11298        protected EphemeralResolveIntentInfo[] newArray(int size) {
11299            return new EphemeralResolveIntentInfo[size];
11300        }
11301
11302        @Override
11303        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11304            return true;
11305        }
11306
11307        @Override
11308        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11309                int userId) {
11310            if (!sUserManager.exists(userId)) {
11311                return null;
11312            }
11313            return info.getEphemeralResolveInfo();
11314        }
11315    }
11316
11317    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11318            new Comparator<ResolveInfo>() {
11319        public int compare(ResolveInfo r1, ResolveInfo r2) {
11320            int v1 = r1.priority;
11321            int v2 = r2.priority;
11322            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11323            if (v1 != v2) {
11324                return (v1 > v2) ? -1 : 1;
11325            }
11326            v1 = r1.preferredOrder;
11327            v2 = r2.preferredOrder;
11328            if (v1 != v2) {
11329                return (v1 > v2) ? -1 : 1;
11330            }
11331            if (r1.isDefault != r2.isDefault) {
11332                return r1.isDefault ? -1 : 1;
11333            }
11334            v1 = r1.match;
11335            v2 = r2.match;
11336            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11337            if (v1 != v2) {
11338                return (v1 > v2) ? -1 : 1;
11339            }
11340            if (r1.system != r2.system) {
11341                return r1.system ? -1 : 1;
11342            }
11343            if (r1.activityInfo != null) {
11344                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11345            }
11346            if (r1.serviceInfo != null) {
11347                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11348            }
11349            if (r1.providerInfo != null) {
11350                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11351            }
11352            return 0;
11353        }
11354    };
11355
11356    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11357            new Comparator<ProviderInfo>() {
11358        public int compare(ProviderInfo p1, ProviderInfo p2) {
11359            final int v1 = p1.initOrder;
11360            final int v2 = p2.initOrder;
11361            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11362        }
11363    };
11364
11365    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11366            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11367            final int[] userIds) {
11368        mHandler.post(new Runnable() {
11369            @Override
11370            public void run() {
11371                try {
11372                    final IActivityManager am = ActivityManagerNative.getDefault();
11373                    if (am == null) return;
11374                    final int[] resolvedUserIds;
11375                    if (userIds == null) {
11376                        resolvedUserIds = am.getRunningUserIds();
11377                    } else {
11378                        resolvedUserIds = userIds;
11379                    }
11380                    for (int id : resolvedUserIds) {
11381                        final Intent intent = new Intent(action,
11382                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11383                        if (extras != null) {
11384                            intent.putExtras(extras);
11385                        }
11386                        if (targetPkg != null) {
11387                            intent.setPackage(targetPkg);
11388                        }
11389                        // Modify the UID when posting to other users
11390                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11391                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11392                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11393                            intent.putExtra(Intent.EXTRA_UID, uid);
11394                        }
11395                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11396                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11397                        if (DEBUG_BROADCASTS) {
11398                            RuntimeException here = new RuntimeException("here");
11399                            here.fillInStackTrace();
11400                            Slog.d(TAG, "Sending to user " + id + ": "
11401                                    + intent.toShortString(false, true, false, false)
11402                                    + " " + intent.getExtras(), here);
11403                        }
11404                        am.broadcastIntent(null, intent, null, finishedReceiver,
11405                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11406                                null, finishedReceiver != null, false, id);
11407                    }
11408                } catch (RemoteException ex) {
11409                }
11410            }
11411        });
11412    }
11413
11414    /**
11415     * Check if the external storage media is available. This is true if there
11416     * is a mounted external storage medium or if the external storage is
11417     * emulated.
11418     */
11419    private boolean isExternalMediaAvailable() {
11420        return mMediaMounted || Environment.isExternalStorageEmulated();
11421    }
11422
11423    @Override
11424    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11425        // writer
11426        synchronized (mPackages) {
11427            if (!isExternalMediaAvailable()) {
11428                // If the external storage is no longer mounted at this point,
11429                // the caller may not have been able to delete all of this
11430                // packages files and can not delete any more.  Bail.
11431                return null;
11432            }
11433            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11434            if (lastPackage != null) {
11435                pkgs.remove(lastPackage);
11436            }
11437            if (pkgs.size() > 0) {
11438                return pkgs.get(0);
11439            }
11440        }
11441        return null;
11442    }
11443
11444    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11445        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11446                userId, andCode ? 1 : 0, packageName);
11447        if (mSystemReady) {
11448            msg.sendToTarget();
11449        } else {
11450            if (mPostSystemReadyMessages == null) {
11451                mPostSystemReadyMessages = new ArrayList<>();
11452            }
11453            mPostSystemReadyMessages.add(msg);
11454        }
11455    }
11456
11457    void startCleaningPackages() {
11458        // reader
11459        if (!isExternalMediaAvailable()) {
11460            return;
11461        }
11462        synchronized (mPackages) {
11463            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11464                return;
11465            }
11466        }
11467        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11468        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11469        IActivityManager am = ActivityManagerNative.getDefault();
11470        if (am != null) {
11471            try {
11472                am.startService(null, intent, null, mContext.getOpPackageName(),
11473                        UserHandle.USER_SYSTEM);
11474            } catch (RemoteException e) {
11475            }
11476        }
11477    }
11478
11479    @Override
11480    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11481            int installFlags, String installerPackageName, int userId) {
11482        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11483
11484        final int callingUid = Binder.getCallingUid();
11485        enforceCrossUserPermission(callingUid, userId,
11486                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11487
11488        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11489            try {
11490                if (observer != null) {
11491                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11492                }
11493            } catch (RemoteException re) {
11494            }
11495            return;
11496        }
11497
11498        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11499            installFlags |= PackageManager.INSTALL_FROM_ADB;
11500
11501        } else {
11502            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11503            // about installerPackageName.
11504
11505            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11506            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11507        }
11508
11509        UserHandle user;
11510        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11511            user = UserHandle.ALL;
11512        } else {
11513            user = new UserHandle(userId);
11514        }
11515
11516        // Only system components can circumvent runtime permissions when installing.
11517        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11518                && mContext.checkCallingOrSelfPermission(Manifest.permission
11519                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11520            throw new SecurityException("You need the "
11521                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11522                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11523        }
11524
11525        final File originFile = new File(originPath);
11526        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11527
11528        final Message msg = mHandler.obtainMessage(INIT_COPY);
11529        final VerificationInfo verificationInfo = new VerificationInfo(
11530                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11531        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11532                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11533                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11534                null /*certificates*/);
11535        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11536        msg.obj = params;
11537
11538        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11539                System.identityHashCode(msg.obj));
11540        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11541                System.identityHashCode(msg.obj));
11542
11543        mHandler.sendMessage(msg);
11544    }
11545
11546    void installStage(String packageName, File stagedDir, String stagedCid,
11547            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11548            String installerPackageName, int installerUid, UserHandle user,
11549            Certificate[][] certificates) {
11550        if (DEBUG_EPHEMERAL) {
11551            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11552                Slog.d(TAG, "Ephemeral install of " + packageName);
11553            }
11554        }
11555        final VerificationInfo verificationInfo = new VerificationInfo(
11556                sessionParams.originatingUri, sessionParams.referrerUri,
11557                sessionParams.originatingUid, installerUid);
11558
11559        final OriginInfo origin;
11560        if (stagedDir != null) {
11561            origin = OriginInfo.fromStagedFile(stagedDir);
11562        } else {
11563            origin = OriginInfo.fromStagedContainer(stagedCid);
11564        }
11565
11566        final Message msg = mHandler.obtainMessage(INIT_COPY);
11567        final InstallParams params = new InstallParams(origin, null, observer,
11568                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11569                verificationInfo, user, sessionParams.abiOverride,
11570                sessionParams.grantedRuntimePermissions, certificates);
11571        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11572        msg.obj = params;
11573
11574        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11575                System.identityHashCode(msg.obj));
11576        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11577                System.identityHashCode(msg.obj));
11578
11579        mHandler.sendMessage(msg);
11580    }
11581
11582    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11583            int userId) {
11584        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11585        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11586    }
11587
11588    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11589            int appId, int userId) {
11590        Bundle extras = new Bundle(1);
11591        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11592
11593        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11594                packageName, extras, 0, null, null, new int[] {userId});
11595        try {
11596            IActivityManager am = ActivityManagerNative.getDefault();
11597            if (isSystem && am.isUserRunning(userId, 0)) {
11598                // The just-installed/enabled app is bundled on the system, so presumed
11599                // to be able to run automatically without needing an explicit launch.
11600                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11601                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11602                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11603                        .setPackage(packageName);
11604                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11605                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11606            }
11607        } catch (RemoteException e) {
11608            // shouldn't happen
11609            Slog.w(TAG, "Unable to bootstrap installed package", e);
11610        }
11611    }
11612
11613    @Override
11614    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11615            int userId) {
11616        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11617        PackageSetting pkgSetting;
11618        final int uid = Binder.getCallingUid();
11619        enforceCrossUserPermission(uid, userId,
11620                true /* requireFullPermission */, true /* checkShell */,
11621                "setApplicationHiddenSetting for user " + userId);
11622
11623        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11624            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11625            return false;
11626        }
11627
11628        long callingId = Binder.clearCallingIdentity();
11629        try {
11630            boolean sendAdded = false;
11631            boolean sendRemoved = false;
11632            // writer
11633            synchronized (mPackages) {
11634                pkgSetting = mSettings.mPackages.get(packageName);
11635                if (pkgSetting == null) {
11636                    return false;
11637                }
11638                if (pkgSetting.getHidden(userId) != hidden) {
11639                    pkgSetting.setHidden(hidden, userId);
11640                    mSettings.writePackageRestrictionsLPr(userId);
11641                    if (hidden) {
11642                        sendRemoved = true;
11643                    } else {
11644                        sendAdded = true;
11645                    }
11646                }
11647            }
11648            if (sendAdded) {
11649                sendPackageAddedForUser(packageName, pkgSetting, userId);
11650                return true;
11651            }
11652            if (sendRemoved) {
11653                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11654                        "hiding pkg");
11655                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11656                return true;
11657            }
11658        } finally {
11659            Binder.restoreCallingIdentity(callingId);
11660        }
11661        return false;
11662    }
11663
11664    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11665            int userId) {
11666        final PackageRemovedInfo info = new PackageRemovedInfo();
11667        info.removedPackage = packageName;
11668        info.removedUsers = new int[] {userId};
11669        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11670        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11671    }
11672
11673    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11674        if (pkgList.length > 0) {
11675            Bundle extras = new Bundle(1);
11676            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11677
11678            sendPackageBroadcast(
11679                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11680                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11681                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11682                    new int[] {userId});
11683        }
11684    }
11685
11686    /**
11687     * Returns true if application is not found or there was an error. Otherwise it returns
11688     * the hidden state of the package for the given user.
11689     */
11690    @Override
11691    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11692        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11693        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11694                true /* requireFullPermission */, false /* checkShell */,
11695                "getApplicationHidden for user " + userId);
11696        PackageSetting pkgSetting;
11697        long callingId = Binder.clearCallingIdentity();
11698        try {
11699            // writer
11700            synchronized (mPackages) {
11701                pkgSetting = mSettings.mPackages.get(packageName);
11702                if (pkgSetting == null) {
11703                    return true;
11704                }
11705                return pkgSetting.getHidden(userId);
11706            }
11707        } finally {
11708            Binder.restoreCallingIdentity(callingId);
11709        }
11710    }
11711
11712    /**
11713     * @hide
11714     */
11715    @Override
11716    public int installExistingPackageAsUser(String packageName, int userId) {
11717        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11718                null);
11719        PackageSetting pkgSetting;
11720        final int uid = Binder.getCallingUid();
11721        enforceCrossUserPermission(uid, userId,
11722                true /* requireFullPermission */, true /* checkShell */,
11723                "installExistingPackage for user " + userId);
11724        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11725            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11726        }
11727
11728        long callingId = Binder.clearCallingIdentity();
11729        try {
11730            boolean installed = false;
11731
11732            // writer
11733            synchronized (mPackages) {
11734                pkgSetting = mSettings.mPackages.get(packageName);
11735                if (pkgSetting == null) {
11736                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11737                }
11738                if (!pkgSetting.getInstalled(userId)) {
11739                    pkgSetting.setInstalled(true, userId);
11740                    pkgSetting.setHidden(false, userId);
11741                    mSettings.writePackageRestrictionsLPr(userId);
11742                    installed = true;
11743                }
11744            }
11745
11746            if (installed) {
11747                if (pkgSetting.pkg != null) {
11748                    synchronized (mInstallLock) {
11749                        // We don't need to freeze for a brand new install
11750                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11751                    }
11752                }
11753                sendPackageAddedForUser(packageName, pkgSetting, userId);
11754            }
11755        } finally {
11756            Binder.restoreCallingIdentity(callingId);
11757        }
11758
11759        return PackageManager.INSTALL_SUCCEEDED;
11760    }
11761
11762    boolean isUserRestricted(int userId, String restrictionKey) {
11763        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11764        if (restrictions.getBoolean(restrictionKey, false)) {
11765            Log.w(TAG, "User is restricted: " + restrictionKey);
11766            return true;
11767        }
11768        return false;
11769    }
11770
11771    @Override
11772    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11773            int userId) {
11774        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11775        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11776                true /* requireFullPermission */, true /* checkShell */,
11777                "setPackagesSuspended for user " + userId);
11778
11779        if (ArrayUtils.isEmpty(packageNames)) {
11780            return packageNames;
11781        }
11782
11783        // List of package names for whom the suspended state has changed.
11784        List<String> changedPackages = new ArrayList<>(packageNames.length);
11785        // List of package names for whom the suspended state is not set as requested in this
11786        // method.
11787        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11788        long callingId = Binder.clearCallingIdentity();
11789        try {
11790            for (int i = 0; i < packageNames.length; i++) {
11791                String packageName = packageNames[i];
11792                boolean changed = false;
11793                final int appId;
11794                synchronized (mPackages) {
11795                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11796                    if (pkgSetting == null) {
11797                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11798                                + "\". Skipping suspending/un-suspending.");
11799                        unactionedPackages.add(packageName);
11800                        continue;
11801                    }
11802                    appId = pkgSetting.appId;
11803                    if (pkgSetting.getSuspended(userId) != suspended) {
11804                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11805                            unactionedPackages.add(packageName);
11806                            continue;
11807                        }
11808                        pkgSetting.setSuspended(suspended, userId);
11809                        mSettings.writePackageRestrictionsLPr(userId);
11810                        changed = true;
11811                        changedPackages.add(packageName);
11812                    }
11813                }
11814
11815                if (changed && suspended) {
11816                    killApplication(packageName, UserHandle.getUid(userId, appId),
11817                            "suspending package");
11818                }
11819            }
11820        } finally {
11821            Binder.restoreCallingIdentity(callingId);
11822        }
11823
11824        if (!changedPackages.isEmpty()) {
11825            sendPackagesSuspendedForUser(changedPackages.toArray(
11826                    new String[changedPackages.size()]), userId, suspended);
11827        }
11828
11829        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11830    }
11831
11832    @Override
11833    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11834        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11835                true /* requireFullPermission */, false /* checkShell */,
11836                "isPackageSuspendedForUser for user " + userId);
11837        synchronized (mPackages) {
11838            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11839            if (pkgSetting == null) {
11840                throw new IllegalArgumentException("Unknown target package: " + packageName);
11841            }
11842            return pkgSetting.getSuspended(userId);
11843        }
11844    }
11845
11846    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11847        if (isPackageDeviceAdmin(packageName, userId)) {
11848            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11849                    + "\": has an active device admin");
11850            return false;
11851        }
11852
11853        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11854        if (packageName.equals(activeLauncherPackageName)) {
11855            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11856                    + "\": contains the active launcher");
11857            return false;
11858        }
11859
11860        if (packageName.equals(mRequiredInstallerPackage)) {
11861            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11862                    + "\": required for package installation");
11863            return false;
11864        }
11865
11866        if (packageName.equals(mRequiredVerifierPackage)) {
11867            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11868                    + "\": required for package verification");
11869            return false;
11870        }
11871
11872        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11873            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11874                    + "\": is the default dialer");
11875            return false;
11876        }
11877
11878        return true;
11879    }
11880
11881    private String getActiveLauncherPackageName(int userId) {
11882        Intent intent = new Intent(Intent.ACTION_MAIN);
11883        intent.addCategory(Intent.CATEGORY_HOME);
11884        ResolveInfo resolveInfo = resolveIntent(
11885                intent,
11886                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11887                PackageManager.MATCH_DEFAULT_ONLY,
11888                userId);
11889
11890        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11891    }
11892
11893    private String getDefaultDialerPackageName(int userId) {
11894        synchronized (mPackages) {
11895            return mSettings.getDefaultDialerPackageNameLPw(userId);
11896        }
11897    }
11898
11899    @Override
11900    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11901        mContext.enforceCallingOrSelfPermission(
11902                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11903                "Only package verification agents can verify applications");
11904
11905        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11906        final PackageVerificationResponse response = new PackageVerificationResponse(
11907                verificationCode, Binder.getCallingUid());
11908        msg.arg1 = id;
11909        msg.obj = response;
11910        mHandler.sendMessage(msg);
11911    }
11912
11913    @Override
11914    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11915            long millisecondsToDelay) {
11916        mContext.enforceCallingOrSelfPermission(
11917                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11918                "Only package verification agents can extend verification timeouts");
11919
11920        final PackageVerificationState state = mPendingVerification.get(id);
11921        final PackageVerificationResponse response = new PackageVerificationResponse(
11922                verificationCodeAtTimeout, Binder.getCallingUid());
11923
11924        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11925            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11926        }
11927        if (millisecondsToDelay < 0) {
11928            millisecondsToDelay = 0;
11929        }
11930        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11931                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11932            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11933        }
11934
11935        if ((state != null) && !state.timeoutExtended()) {
11936            state.extendTimeout();
11937
11938            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11939            msg.arg1 = id;
11940            msg.obj = response;
11941            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11942        }
11943    }
11944
11945    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11946            int verificationCode, UserHandle user) {
11947        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11948        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11949        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11950        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11951        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11952
11953        mContext.sendBroadcastAsUser(intent, user,
11954                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11955    }
11956
11957    private ComponentName matchComponentForVerifier(String packageName,
11958            List<ResolveInfo> receivers) {
11959        ActivityInfo targetReceiver = null;
11960
11961        final int NR = receivers.size();
11962        for (int i = 0; i < NR; i++) {
11963            final ResolveInfo info = receivers.get(i);
11964            if (info.activityInfo == null) {
11965                continue;
11966            }
11967
11968            if (packageName.equals(info.activityInfo.packageName)) {
11969                targetReceiver = info.activityInfo;
11970                break;
11971            }
11972        }
11973
11974        if (targetReceiver == null) {
11975            return null;
11976        }
11977
11978        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11979    }
11980
11981    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11982            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11983        if (pkgInfo.verifiers.length == 0) {
11984            return null;
11985        }
11986
11987        final int N = pkgInfo.verifiers.length;
11988        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11989        for (int i = 0; i < N; i++) {
11990            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11991
11992            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11993                    receivers);
11994            if (comp == null) {
11995                continue;
11996            }
11997
11998            final int verifierUid = getUidForVerifier(verifierInfo);
11999            if (verifierUid == -1) {
12000                continue;
12001            }
12002
12003            if (DEBUG_VERIFY) {
12004                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12005                        + " with the correct signature");
12006            }
12007            sufficientVerifiers.add(comp);
12008            verificationState.addSufficientVerifier(verifierUid);
12009        }
12010
12011        return sufficientVerifiers;
12012    }
12013
12014    private int getUidForVerifier(VerifierInfo verifierInfo) {
12015        synchronized (mPackages) {
12016            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12017            if (pkg == null) {
12018                return -1;
12019            } else if (pkg.mSignatures.length != 1) {
12020                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12021                        + " has more than one signature; ignoring");
12022                return -1;
12023            }
12024
12025            /*
12026             * If the public key of the package's signature does not match
12027             * our expected public key, then this is a different package and
12028             * we should skip.
12029             */
12030
12031            final byte[] expectedPublicKey;
12032            try {
12033                final Signature verifierSig = pkg.mSignatures[0];
12034                final PublicKey publicKey = verifierSig.getPublicKey();
12035                expectedPublicKey = publicKey.getEncoded();
12036            } catch (CertificateException e) {
12037                return -1;
12038            }
12039
12040            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12041
12042            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12043                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12044                        + " does not have the expected public key; ignoring");
12045                return -1;
12046            }
12047
12048            return pkg.applicationInfo.uid;
12049        }
12050    }
12051
12052    @Override
12053    public void finishPackageInstall(int token, boolean didLaunch) {
12054        enforceSystemOrRoot("Only the system is allowed to finish installs");
12055
12056        if (DEBUG_INSTALL) {
12057            Slog.v(TAG, "BM finishing package install for " + token);
12058        }
12059        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12060
12061        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12062        mHandler.sendMessage(msg);
12063    }
12064
12065    /**
12066     * Get the verification agent timeout.
12067     *
12068     * @return verification timeout in milliseconds
12069     */
12070    private long getVerificationTimeout() {
12071        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12072                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12073                DEFAULT_VERIFICATION_TIMEOUT);
12074    }
12075
12076    /**
12077     * Get the default verification agent response code.
12078     *
12079     * @return default verification response code
12080     */
12081    private int getDefaultVerificationResponse() {
12082        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12083                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12084                DEFAULT_VERIFICATION_RESPONSE);
12085    }
12086
12087    /**
12088     * Check whether or not package verification has been enabled.
12089     *
12090     * @return true if verification should be performed
12091     */
12092    private boolean isVerificationEnabled(int userId, int installFlags) {
12093        if (!DEFAULT_VERIFY_ENABLE) {
12094            return false;
12095        }
12096        // Ephemeral apps don't get the full verification treatment
12097        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12098            if (DEBUG_EPHEMERAL) {
12099                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12100            }
12101            return false;
12102        }
12103
12104        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12105
12106        // Check if installing from ADB
12107        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12108            // Do not run verification in a test harness environment
12109            if (ActivityManager.isRunningInTestHarness()) {
12110                return false;
12111            }
12112            if (ensureVerifyAppsEnabled) {
12113                return true;
12114            }
12115            // Check if the developer does not want package verification for ADB installs
12116            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12117                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12118                return false;
12119            }
12120        }
12121
12122        if (ensureVerifyAppsEnabled) {
12123            return true;
12124        }
12125
12126        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12127                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12128    }
12129
12130    @Override
12131    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12132            throws RemoteException {
12133        mContext.enforceCallingOrSelfPermission(
12134                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12135                "Only intentfilter verification agents can verify applications");
12136
12137        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12138        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12139                Binder.getCallingUid(), verificationCode, failedDomains);
12140        msg.arg1 = id;
12141        msg.obj = response;
12142        mHandler.sendMessage(msg);
12143    }
12144
12145    @Override
12146    public int getIntentVerificationStatus(String packageName, int userId) {
12147        synchronized (mPackages) {
12148            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12149        }
12150    }
12151
12152    @Override
12153    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12154        mContext.enforceCallingOrSelfPermission(
12155                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12156
12157        boolean result = false;
12158        synchronized (mPackages) {
12159            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12160        }
12161        if (result) {
12162            scheduleWritePackageRestrictionsLocked(userId);
12163        }
12164        return result;
12165    }
12166
12167    @Override
12168    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12169            String packageName) {
12170        synchronized (mPackages) {
12171            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12172        }
12173    }
12174
12175    @Override
12176    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12177        if (TextUtils.isEmpty(packageName)) {
12178            return ParceledListSlice.emptyList();
12179        }
12180        synchronized (mPackages) {
12181            PackageParser.Package pkg = mPackages.get(packageName);
12182            if (pkg == null || pkg.activities == null) {
12183                return ParceledListSlice.emptyList();
12184            }
12185            final int count = pkg.activities.size();
12186            ArrayList<IntentFilter> result = new ArrayList<>();
12187            for (int n=0; n<count; n++) {
12188                PackageParser.Activity activity = pkg.activities.get(n);
12189                if (activity.intents != null && activity.intents.size() > 0) {
12190                    result.addAll(activity.intents);
12191                }
12192            }
12193            return new ParceledListSlice<>(result);
12194        }
12195    }
12196
12197    @Override
12198    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12199        mContext.enforceCallingOrSelfPermission(
12200                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12201
12202        synchronized (mPackages) {
12203            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12204            if (packageName != null) {
12205                result |= updateIntentVerificationStatus(packageName,
12206                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12207                        userId);
12208                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12209                        packageName, userId);
12210            }
12211            return result;
12212        }
12213    }
12214
12215    @Override
12216    public String getDefaultBrowserPackageName(int userId) {
12217        synchronized (mPackages) {
12218            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12219        }
12220    }
12221
12222    /**
12223     * Get the "allow unknown sources" setting.
12224     *
12225     * @return the current "allow unknown sources" setting
12226     */
12227    private int getUnknownSourcesSettings() {
12228        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12229                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12230                -1);
12231    }
12232
12233    @Override
12234    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12235        final int uid = Binder.getCallingUid();
12236        // writer
12237        synchronized (mPackages) {
12238            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12239            if (targetPackageSetting == null) {
12240                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12241            }
12242
12243            PackageSetting installerPackageSetting;
12244            if (installerPackageName != null) {
12245                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12246                if (installerPackageSetting == null) {
12247                    throw new IllegalArgumentException("Unknown installer package: "
12248                            + installerPackageName);
12249                }
12250            } else {
12251                installerPackageSetting = null;
12252            }
12253
12254            Signature[] callerSignature;
12255            Object obj = mSettings.getUserIdLPr(uid);
12256            if (obj != null) {
12257                if (obj instanceof SharedUserSetting) {
12258                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12259                } else if (obj instanceof PackageSetting) {
12260                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12261                } else {
12262                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12263                }
12264            } else {
12265                throw new SecurityException("Unknown calling UID: " + uid);
12266            }
12267
12268            // Verify: can't set installerPackageName to a package that is
12269            // not signed with the same cert as the caller.
12270            if (installerPackageSetting != null) {
12271                if (compareSignatures(callerSignature,
12272                        installerPackageSetting.signatures.mSignatures)
12273                        != PackageManager.SIGNATURE_MATCH) {
12274                    throw new SecurityException(
12275                            "Caller does not have same cert as new installer package "
12276                            + installerPackageName);
12277                }
12278            }
12279
12280            // Verify: if target already has an installer package, it must
12281            // be signed with the same cert as the caller.
12282            if (targetPackageSetting.installerPackageName != null) {
12283                PackageSetting setting = mSettings.mPackages.get(
12284                        targetPackageSetting.installerPackageName);
12285                // If the currently set package isn't valid, then it's always
12286                // okay to change it.
12287                if (setting != null) {
12288                    if (compareSignatures(callerSignature,
12289                            setting.signatures.mSignatures)
12290                            != PackageManager.SIGNATURE_MATCH) {
12291                        throw new SecurityException(
12292                                "Caller does not have same cert as old installer package "
12293                                + targetPackageSetting.installerPackageName);
12294                    }
12295                }
12296            }
12297
12298            // Okay!
12299            targetPackageSetting.installerPackageName = installerPackageName;
12300            if (installerPackageName != null) {
12301                mSettings.mInstallerPackages.add(installerPackageName);
12302            }
12303            scheduleWriteSettingsLocked();
12304        }
12305    }
12306
12307    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12308        // Queue up an async operation since the package installation may take a little while.
12309        mHandler.post(new Runnable() {
12310            public void run() {
12311                mHandler.removeCallbacks(this);
12312                 // Result object to be returned
12313                PackageInstalledInfo res = new PackageInstalledInfo();
12314                res.setReturnCode(currentStatus);
12315                res.uid = -1;
12316                res.pkg = null;
12317                res.removedInfo = null;
12318                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12319                    args.doPreInstall(res.returnCode);
12320                    synchronized (mInstallLock) {
12321                        installPackageTracedLI(args, res);
12322                    }
12323                    args.doPostInstall(res.returnCode, res.uid);
12324                }
12325
12326                // A restore should be performed at this point if (a) the install
12327                // succeeded, (b) the operation is not an update, and (c) the new
12328                // package has not opted out of backup participation.
12329                final boolean update = res.removedInfo != null
12330                        && res.removedInfo.removedPackage != null;
12331                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12332                boolean doRestore = !update
12333                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12334
12335                // Set up the post-install work request bookkeeping.  This will be used
12336                // and cleaned up by the post-install event handling regardless of whether
12337                // there's a restore pass performed.  Token values are >= 1.
12338                int token;
12339                if (mNextInstallToken < 0) mNextInstallToken = 1;
12340                token = mNextInstallToken++;
12341
12342                PostInstallData data = new PostInstallData(args, res);
12343                mRunningInstalls.put(token, data);
12344                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12345
12346                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12347                    // Pass responsibility to the Backup Manager.  It will perform a
12348                    // restore if appropriate, then pass responsibility back to the
12349                    // Package Manager to run the post-install observer callbacks
12350                    // and broadcasts.
12351                    IBackupManager bm = IBackupManager.Stub.asInterface(
12352                            ServiceManager.getService(Context.BACKUP_SERVICE));
12353                    if (bm != null) {
12354                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12355                                + " to BM for possible restore");
12356                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12357                        try {
12358                            // TODO: http://b/22388012
12359                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12360                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12361                            } else {
12362                                doRestore = false;
12363                            }
12364                        } catch (RemoteException e) {
12365                            // can't happen; the backup manager is local
12366                        } catch (Exception e) {
12367                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12368                            doRestore = false;
12369                        }
12370                    } else {
12371                        Slog.e(TAG, "Backup Manager not found!");
12372                        doRestore = false;
12373                    }
12374                }
12375
12376                if (!doRestore) {
12377                    // No restore possible, or the Backup Manager was mysteriously not
12378                    // available -- just fire the post-install work request directly.
12379                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12380
12381                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12382
12383                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12384                    mHandler.sendMessage(msg);
12385                }
12386            }
12387        });
12388    }
12389
12390    /**
12391     * Callback from PackageSettings whenever an app is first transitioned out of the
12392     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12393     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12394     * here whether the app is the target of an ongoing install, and only send the
12395     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12396     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12397     * handling.
12398     */
12399    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12400        // Serialize this with the rest of the install-process message chain.  In the
12401        // restore-at-install case, this Runnable will necessarily run before the
12402        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12403        // are coherent.  In the non-restore case, the app has already completed install
12404        // and been launched through some other means, so it is not in a problematic
12405        // state for observers to see the FIRST_LAUNCH signal.
12406        mHandler.post(new Runnable() {
12407            @Override
12408            public void run() {
12409                for (int i = 0; i < mRunningInstalls.size(); i++) {
12410                    final PostInstallData data = mRunningInstalls.valueAt(i);
12411                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12412                        // right package; but is it for the right user?
12413                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12414                            if (userId == data.res.newUsers[uIndex]) {
12415                                if (DEBUG_BACKUP) {
12416                                    Slog.i(TAG, "Package " + pkgName
12417                                            + " being restored so deferring FIRST_LAUNCH");
12418                                }
12419                                return;
12420                            }
12421                        }
12422                    }
12423                }
12424                // didn't find it, so not being restored
12425                if (DEBUG_BACKUP) {
12426                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12427                }
12428                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12429            }
12430        });
12431    }
12432
12433    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12434        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12435                installerPkg, null, userIds);
12436    }
12437
12438    private abstract class HandlerParams {
12439        private static final int MAX_RETRIES = 4;
12440
12441        /**
12442         * Number of times startCopy() has been attempted and had a non-fatal
12443         * error.
12444         */
12445        private int mRetries = 0;
12446
12447        /** User handle for the user requesting the information or installation. */
12448        private final UserHandle mUser;
12449        String traceMethod;
12450        int traceCookie;
12451
12452        HandlerParams(UserHandle user) {
12453            mUser = user;
12454        }
12455
12456        UserHandle getUser() {
12457            return mUser;
12458        }
12459
12460        HandlerParams setTraceMethod(String traceMethod) {
12461            this.traceMethod = traceMethod;
12462            return this;
12463        }
12464
12465        HandlerParams setTraceCookie(int traceCookie) {
12466            this.traceCookie = traceCookie;
12467            return this;
12468        }
12469
12470        final boolean startCopy() {
12471            boolean res;
12472            try {
12473                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12474
12475                if (++mRetries > MAX_RETRIES) {
12476                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12477                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12478                    handleServiceError();
12479                    return false;
12480                } else {
12481                    handleStartCopy();
12482                    res = true;
12483                }
12484            } catch (RemoteException e) {
12485                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12486                mHandler.sendEmptyMessage(MCS_RECONNECT);
12487                res = false;
12488            }
12489            handleReturnCode();
12490            return res;
12491        }
12492
12493        final void serviceError() {
12494            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12495            handleServiceError();
12496            handleReturnCode();
12497        }
12498
12499        abstract void handleStartCopy() throws RemoteException;
12500        abstract void handleServiceError();
12501        abstract void handleReturnCode();
12502    }
12503
12504    class MeasureParams extends HandlerParams {
12505        private final PackageStats mStats;
12506        private boolean mSuccess;
12507
12508        private final IPackageStatsObserver mObserver;
12509
12510        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12511            super(new UserHandle(stats.userHandle));
12512            mObserver = observer;
12513            mStats = stats;
12514        }
12515
12516        @Override
12517        public String toString() {
12518            return "MeasureParams{"
12519                + Integer.toHexString(System.identityHashCode(this))
12520                + " " + mStats.packageName + "}";
12521        }
12522
12523        @Override
12524        void handleStartCopy() throws RemoteException {
12525            synchronized (mInstallLock) {
12526                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12527            }
12528
12529            if (mSuccess) {
12530                final boolean mounted;
12531                if (Environment.isExternalStorageEmulated()) {
12532                    mounted = true;
12533                } else {
12534                    final String status = Environment.getExternalStorageState();
12535                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12536                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12537                }
12538
12539                if (mounted) {
12540                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12541
12542                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12543                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12544
12545                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12546                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12547
12548                    // Always subtract cache size, since it's a subdirectory
12549                    mStats.externalDataSize -= mStats.externalCacheSize;
12550
12551                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12552                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12553
12554                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12555                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12556                }
12557            }
12558        }
12559
12560        @Override
12561        void handleReturnCode() {
12562            if (mObserver != null) {
12563                try {
12564                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12565                } catch (RemoteException e) {
12566                    Slog.i(TAG, "Observer no longer exists.");
12567                }
12568            }
12569        }
12570
12571        @Override
12572        void handleServiceError() {
12573            Slog.e(TAG, "Could not measure application " + mStats.packageName
12574                            + " external storage");
12575        }
12576    }
12577
12578    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12579            throws RemoteException {
12580        long result = 0;
12581        for (File path : paths) {
12582            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12583        }
12584        return result;
12585    }
12586
12587    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12588        for (File path : paths) {
12589            try {
12590                mcs.clearDirectory(path.getAbsolutePath());
12591            } catch (RemoteException e) {
12592            }
12593        }
12594    }
12595
12596    static class OriginInfo {
12597        /**
12598         * Location where install is coming from, before it has been
12599         * copied/renamed into place. This could be a single monolithic APK
12600         * file, or a cluster directory. This location may be untrusted.
12601         */
12602        final File file;
12603        final String cid;
12604
12605        /**
12606         * Flag indicating that {@link #file} or {@link #cid} has already been
12607         * staged, meaning downstream users don't need to defensively copy the
12608         * contents.
12609         */
12610        final boolean staged;
12611
12612        /**
12613         * Flag indicating that {@link #file} or {@link #cid} is an already
12614         * installed app that is being moved.
12615         */
12616        final boolean existing;
12617
12618        final String resolvedPath;
12619        final File resolvedFile;
12620
12621        static OriginInfo fromNothing() {
12622            return new OriginInfo(null, null, false, false);
12623        }
12624
12625        static OriginInfo fromUntrustedFile(File file) {
12626            return new OriginInfo(file, null, false, false);
12627        }
12628
12629        static OriginInfo fromExistingFile(File file) {
12630            return new OriginInfo(file, null, false, true);
12631        }
12632
12633        static OriginInfo fromStagedFile(File file) {
12634            return new OriginInfo(file, null, true, false);
12635        }
12636
12637        static OriginInfo fromStagedContainer(String cid) {
12638            return new OriginInfo(null, cid, true, false);
12639        }
12640
12641        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12642            this.file = file;
12643            this.cid = cid;
12644            this.staged = staged;
12645            this.existing = existing;
12646
12647            if (cid != null) {
12648                resolvedPath = PackageHelper.getSdDir(cid);
12649                resolvedFile = new File(resolvedPath);
12650            } else if (file != null) {
12651                resolvedPath = file.getAbsolutePath();
12652                resolvedFile = file;
12653            } else {
12654                resolvedPath = null;
12655                resolvedFile = null;
12656            }
12657        }
12658    }
12659
12660    static class MoveInfo {
12661        final int moveId;
12662        final String fromUuid;
12663        final String toUuid;
12664        final String packageName;
12665        final String dataAppName;
12666        final int appId;
12667        final String seinfo;
12668        final int targetSdkVersion;
12669
12670        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12671                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12672            this.moveId = moveId;
12673            this.fromUuid = fromUuid;
12674            this.toUuid = toUuid;
12675            this.packageName = packageName;
12676            this.dataAppName = dataAppName;
12677            this.appId = appId;
12678            this.seinfo = seinfo;
12679            this.targetSdkVersion = targetSdkVersion;
12680        }
12681    }
12682
12683    static class VerificationInfo {
12684        /** A constant used to indicate that a uid value is not present. */
12685        public static final int NO_UID = -1;
12686
12687        /** URI referencing where the package was downloaded from. */
12688        final Uri originatingUri;
12689
12690        /** HTTP referrer URI associated with the originatingURI. */
12691        final Uri referrer;
12692
12693        /** UID of the application that the install request originated from. */
12694        final int originatingUid;
12695
12696        /** UID of application requesting the install */
12697        final int installerUid;
12698
12699        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12700            this.originatingUri = originatingUri;
12701            this.referrer = referrer;
12702            this.originatingUid = originatingUid;
12703            this.installerUid = installerUid;
12704        }
12705    }
12706
12707    class InstallParams extends HandlerParams {
12708        final OriginInfo origin;
12709        final MoveInfo move;
12710        final IPackageInstallObserver2 observer;
12711        int installFlags;
12712        final String installerPackageName;
12713        final String volumeUuid;
12714        private InstallArgs mArgs;
12715        private int mRet;
12716        final String packageAbiOverride;
12717        final String[] grantedRuntimePermissions;
12718        final VerificationInfo verificationInfo;
12719        final Certificate[][] certificates;
12720
12721        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12722                int installFlags, String installerPackageName, String volumeUuid,
12723                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12724                String[] grantedPermissions, Certificate[][] certificates) {
12725            super(user);
12726            this.origin = origin;
12727            this.move = move;
12728            this.observer = observer;
12729            this.installFlags = installFlags;
12730            this.installerPackageName = installerPackageName;
12731            this.volumeUuid = volumeUuid;
12732            this.verificationInfo = verificationInfo;
12733            this.packageAbiOverride = packageAbiOverride;
12734            this.grantedRuntimePermissions = grantedPermissions;
12735            this.certificates = certificates;
12736        }
12737
12738        @Override
12739        public String toString() {
12740            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12741                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12742        }
12743
12744        private int installLocationPolicy(PackageInfoLite pkgLite) {
12745            String packageName = pkgLite.packageName;
12746            int installLocation = pkgLite.installLocation;
12747            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12748            // reader
12749            synchronized (mPackages) {
12750                // Currently installed package which the new package is attempting to replace or
12751                // null if no such package is installed.
12752                PackageParser.Package installedPkg = mPackages.get(packageName);
12753                // Package which currently owns the data which the new package will own if installed.
12754                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12755                // will be null whereas dataOwnerPkg will contain information about the package
12756                // which was uninstalled while keeping its data.
12757                PackageParser.Package dataOwnerPkg = installedPkg;
12758                if (dataOwnerPkg  == null) {
12759                    PackageSetting ps = mSettings.mPackages.get(packageName);
12760                    if (ps != null) {
12761                        dataOwnerPkg = ps.pkg;
12762                    }
12763                }
12764
12765                if (dataOwnerPkg != null) {
12766                    // If installed, the package will get access to data left on the device by its
12767                    // predecessor. As a security measure, this is permited only if this is not a
12768                    // version downgrade or if the predecessor package is marked as debuggable and
12769                    // a downgrade is explicitly requested.
12770                    //
12771                    // On debuggable platform builds, downgrades are permitted even for
12772                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12773                    // not offer security guarantees and thus it's OK to disable some security
12774                    // mechanisms to make debugging/testing easier on those builds. However, even on
12775                    // debuggable builds downgrades of packages are permitted only if requested via
12776                    // installFlags. This is because we aim to keep the behavior of debuggable
12777                    // platform builds as close as possible to the behavior of non-debuggable
12778                    // platform builds.
12779                    final boolean downgradeRequested =
12780                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12781                    final boolean packageDebuggable =
12782                                (dataOwnerPkg.applicationInfo.flags
12783                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12784                    final boolean downgradePermitted =
12785                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12786                    if (!downgradePermitted) {
12787                        try {
12788                            checkDowngrade(dataOwnerPkg, pkgLite);
12789                        } catch (PackageManagerException e) {
12790                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12791                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12792                        }
12793                    }
12794                }
12795
12796                if (installedPkg != null) {
12797                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12798                        // Check for updated system application.
12799                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12800                            if (onSd) {
12801                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12802                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12803                            }
12804                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12805                        } else {
12806                            if (onSd) {
12807                                // Install flag overrides everything.
12808                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12809                            }
12810                            // If current upgrade specifies particular preference
12811                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12812                                // Application explicitly specified internal.
12813                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12814                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12815                                // App explictly prefers external. Let policy decide
12816                            } else {
12817                                // Prefer previous location
12818                                if (isExternal(installedPkg)) {
12819                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12820                                }
12821                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12822                            }
12823                        }
12824                    } else {
12825                        // Invalid install. Return error code
12826                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12827                    }
12828                }
12829            }
12830            // All the special cases have been taken care of.
12831            // Return result based on recommended install location.
12832            if (onSd) {
12833                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12834            }
12835            return pkgLite.recommendedInstallLocation;
12836        }
12837
12838        /*
12839         * Invoke remote method to get package information and install
12840         * location values. Override install location based on default
12841         * policy if needed and then create install arguments based
12842         * on the install location.
12843         */
12844        public void handleStartCopy() throws RemoteException {
12845            int ret = PackageManager.INSTALL_SUCCEEDED;
12846
12847            // If we're already staged, we've firmly committed to an install location
12848            if (origin.staged) {
12849                if (origin.file != null) {
12850                    installFlags |= PackageManager.INSTALL_INTERNAL;
12851                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12852                } else if (origin.cid != null) {
12853                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12854                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12855                } else {
12856                    throw new IllegalStateException("Invalid stage location");
12857                }
12858            }
12859
12860            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12861            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12862            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12863            PackageInfoLite pkgLite = null;
12864
12865            if (onInt && onSd) {
12866                // Check if both bits are set.
12867                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12868                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12869            } else if (onSd && ephemeral) {
12870                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12871                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12872            } else {
12873                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12874                        packageAbiOverride);
12875
12876                if (DEBUG_EPHEMERAL && ephemeral) {
12877                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12878                }
12879
12880                /*
12881                 * If we have too little free space, try to free cache
12882                 * before giving up.
12883                 */
12884                if (!origin.staged && pkgLite.recommendedInstallLocation
12885                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12886                    // TODO: focus freeing disk space on the target device
12887                    final StorageManager storage = StorageManager.from(mContext);
12888                    final long lowThreshold = storage.getStorageLowBytes(
12889                            Environment.getDataDirectory());
12890
12891                    final long sizeBytes = mContainerService.calculateInstalledSize(
12892                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12893
12894                    try {
12895                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12896                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12897                                installFlags, packageAbiOverride);
12898                    } catch (InstallerException e) {
12899                        Slog.w(TAG, "Failed to free cache", e);
12900                    }
12901
12902                    /*
12903                     * The cache free must have deleted the file we
12904                     * downloaded to install.
12905                     *
12906                     * TODO: fix the "freeCache" call to not delete
12907                     *       the file we care about.
12908                     */
12909                    if (pkgLite.recommendedInstallLocation
12910                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12911                        pkgLite.recommendedInstallLocation
12912                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12913                    }
12914                }
12915            }
12916
12917            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12918                int loc = pkgLite.recommendedInstallLocation;
12919                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12920                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12921                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12922                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12923                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12924                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12925                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12926                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12927                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12928                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12929                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12930                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12931                } else {
12932                    // Override with defaults if needed.
12933                    loc = installLocationPolicy(pkgLite);
12934                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12935                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12936                    } else if (!onSd && !onInt) {
12937                        // Override install location with flags
12938                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12939                            // Set the flag to install on external media.
12940                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12941                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12942                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12943                            if (DEBUG_EPHEMERAL) {
12944                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12945                            }
12946                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12947                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12948                                    |PackageManager.INSTALL_INTERNAL);
12949                        } else {
12950                            // Make sure the flag for installing on external
12951                            // media is unset
12952                            installFlags |= PackageManager.INSTALL_INTERNAL;
12953                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12954                        }
12955                    }
12956                }
12957            }
12958
12959            final InstallArgs args = createInstallArgs(this);
12960            mArgs = args;
12961
12962            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12963                // TODO: http://b/22976637
12964                // Apps installed for "all" users use the device owner to verify the app
12965                UserHandle verifierUser = getUser();
12966                if (verifierUser == UserHandle.ALL) {
12967                    verifierUser = UserHandle.SYSTEM;
12968                }
12969
12970                /*
12971                 * Determine if we have any installed package verifiers. If we
12972                 * do, then we'll defer to them to verify the packages.
12973                 */
12974                final int requiredUid = mRequiredVerifierPackage == null ? -1
12975                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12976                                verifierUser.getIdentifier());
12977                if (!origin.existing && requiredUid != -1
12978                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12979                    final Intent verification = new Intent(
12980                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12981                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12982                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12983                            PACKAGE_MIME_TYPE);
12984                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12985
12986                    // Query all live verifiers based on current user state
12987                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12988                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12989
12990                    if (DEBUG_VERIFY) {
12991                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12992                                + verification.toString() + " with " + pkgLite.verifiers.length
12993                                + " optional verifiers");
12994                    }
12995
12996                    final int verificationId = mPendingVerificationToken++;
12997
12998                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12999
13000                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13001                            installerPackageName);
13002
13003                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13004                            installFlags);
13005
13006                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13007                            pkgLite.packageName);
13008
13009                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13010                            pkgLite.versionCode);
13011
13012                    if (verificationInfo != null) {
13013                        if (verificationInfo.originatingUri != null) {
13014                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13015                                    verificationInfo.originatingUri);
13016                        }
13017                        if (verificationInfo.referrer != null) {
13018                            verification.putExtra(Intent.EXTRA_REFERRER,
13019                                    verificationInfo.referrer);
13020                        }
13021                        if (verificationInfo.originatingUid >= 0) {
13022                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13023                                    verificationInfo.originatingUid);
13024                        }
13025                        if (verificationInfo.installerUid >= 0) {
13026                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13027                                    verificationInfo.installerUid);
13028                        }
13029                    }
13030
13031                    final PackageVerificationState verificationState = new PackageVerificationState(
13032                            requiredUid, args);
13033
13034                    mPendingVerification.append(verificationId, verificationState);
13035
13036                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13037                            receivers, verificationState);
13038
13039                    /*
13040                     * If any sufficient verifiers were listed in the package
13041                     * manifest, attempt to ask them.
13042                     */
13043                    if (sufficientVerifiers != null) {
13044                        final int N = sufficientVerifiers.size();
13045                        if (N == 0) {
13046                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13047                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13048                        } else {
13049                            for (int i = 0; i < N; i++) {
13050                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13051
13052                                final Intent sufficientIntent = new Intent(verification);
13053                                sufficientIntent.setComponent(verifierComponent);
13054                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13055                            }
13056                        }
13057                    }
13058
13059                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13060                            mRequiredVerifierPackage, receivers);
13061                    if (ret == PackageManager.INSTALL_SUCCEEDED
13062                            && mRequiredVerifierPackage != null) {
13063                        Trace.asyncTraceBegin(
13064                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13065                        /*
13066                         * Send the intent to the required verification agent,
13067                         * but only start the verification timeout after the
13068                         * target BroadcastReceivers have run.
13069                         */
13070                        verification.setComponent(requiredVerifierComponent);
13071                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13072                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13073                                new BroadcastReceiver() {
13074                                    @Override
13075                                    public void onReceive(Context context, Intent intent) {
13076                                        final Message msg = mHandler
13077                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13078                                        msg.arg1 = verificationId;
13079                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13080                                    }
13081                                }, null, 0, null, null);
13082
13083                        /*
13084                         * We don't want the copy to proceed until verification
13085                         * succeeds, so null out this field.
13086                         */
13087                        mArgs = null;
13088                    }
13089                } else {
13090                    /*
13091                     * No package verification is enabled, so immediately start
13092                     * the remote call to initiate copy using temporary file.
13093                     */
13094                    ret = args.copyApk(mContainerService, true);
13095                }
13096            }
13097
13098            mRet = ret;
13099        }
13100
13101        @Override
13102        void handleReturnCode() {
13103            // If mArgs is null, then MCS couldn't be reached. When it
13104            // reconnects, it will try again to install. At that point, this
13105            // will succeed.
13106            if (mArgs != null) {
13107                processPendingInstall(mArgs, mRet);
13108            }
13109        }
13110
13111        @Override
13112        void handleServiceError() {
13113            mArgs = createInstallArgs(this);
13114            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13115        }
13116
13117        public boolean isForwardLocked() {
13118            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13119        }
13120    }
13121
13122    /**
13123     * Used during creation of InstallArgs
13124     *
13125     * @param installFlags package installation flags
13126     * @return true if should be installed on external storage
13127     */
13128    private static boolean installOnExternalAsec(int installFlags) {
13129        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13130            return false;
13131        }
13132        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13133            return true;
13134        }
13135        return false;
13136    }
13137
13138    /**
13139     * Used during creation of InstallArgs
13140     *
13141     * @param installFlags package installation flags
13142     * @return true if should be installed as forward locked
13143     */
13144    private static boolean installForwardLocked(int installFlags) {
13145        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13146    }
13147
13148    private InstallArgs createInstallArgs(InstallParams params) {
13149        if (params.move != null) {
13150            return new MoveInstallArgs(params);
13151        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13152            return new AsecInstallArgs(params);
13153        } else {
13154            return new FileInstallArgs(params);
13155        }
13156    }
13157
13158    /**
13159     * Create args that describe an existing installed package. Typically used
13160     * when cleaning up old installs, or used as a move source.
13161     */
13162    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13163            String resourcePath, String[] instructionSets) {
13164        final boolean isInAsec;
13165        if (installOnExternalAsec(installFlags)) {
13166            /* Apps on SD card are always in ASEC containers. */
13167            isInAsec = true;
13168        } else if (installForwardLocked(installFlags)
13169                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13170            /*
13171             * Forward-locked apps are only in ASEC containers if they're the
13172             * new style
13173             */
13174            isInAsec = true;
13175        } else {
13176            isInAsec = false;
13177        }
13178
13179        if (isInAsec) {
13180            return new AsecInstallArgs(codePath, instructionSets,
13181                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13182        } else {
13183            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13184        }
13185    }
13186
13187    static abstract class InstallArgs {
13188        /** @see InstallParams#origin */
13189        final OriginInfo origin;
13190        /** @see InstallParams#move */
13191        final MoveInfo move;
13192
13193        final IPackageInstallObserver2 observer;
13194        // Always refers to PackageManager flags only
13195        final int installFlags;
13196        final String installerPackageName;
13197        final String volumeUuid;
13198        final UserHandle user;
13199        final String abiOverride;
13200        final String[] installGrantPermissions;
13201        /** If non-null, drop an async trace when the install completes */
13202        final String traceMethod;
13203        final int traceCookie;
13204        final Certificate[][] certificates;
13205
13206        // The list of instruction sets supported by this app. This is currently
13207        // only used during the rmdex() phase to clean up resources. We can get rid of this
13208        // if we move dex files under the common app path.
13209        /* nullable */ String[] instructionSets;
13210
13211        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13212                int installFlags, String installerPackageName, String volumeUuid,
13213                UserHandle user, String[] instructionSets,
13214                String abiOverride, String[] installGrantPermissions,
13215                String traceMethod, int traceCookie, Certificate[][] certificates) {
13216            this.origin = origin;
13217            this.move = move;
13218            this.installFlags = installFlags;
13219            this.observer = observer;
13220            this.installerPackageName = installerPackageName;
13221            this.volumeUuid = volumeUuid;
13222            this.user = user;
13223            this.instructionSets = instructionSets;
13224            this.abiOverride = abiOverride;
13225            this.installGrantPermissions = installGrantPermissions;
13226            this.traceMethod = traceMethod;
13227            this.traceCookie = traceCookie;
13228            this.certificates = certificates;
13229        }
13230
13231        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13232        abstract int doPreInstall(int status);
13233
13234        /**
13235         * Rename package into final resting place. All paths on the given
13236         * scanned package should be updated to reflect the rename.
13237         */
13238        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13239        abstract int doPostInstall(int status, int uid);
13240
13241        /** @see PackageSettingBase#codePathString */
13242        abstract String getCodePath();
13243        /** @see PackageSettingBase#resourcePathString */
13244        abstract String getResourcePath();
13245
13246        // Need installer lock especially for dex file removal.
13247        abstract void cleanUpResourcesLI();
13248        abstract boolean doPostDeleteLI(boolean delete);
13249
13250        /**
13251         * Called before the source arguments are copied. This is used mostly
13252         * for MoveParams when it needs to read the source file to put it in the
13253         * destination.
13254         */
13255        int doPreCopy() {
13256            return PackageManager.INSTALL_SUCCEEDED;
13257        }
13258
13259        /**
13260         * Called after the source arguments are copied. This is used mostly for
13261         * MoveParams when it needs to read the source file to put it in the
13262         * destination.
13263         */
13264        int doPostCopy(int uid) {
13265            return PackageManager.INSTALL_SUCCEEDED;
13266        }
13267
13268        protected boolean isFwdLocked() {
13269            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13270        }
13271
13272        protected boolean isExternalAsec() {
13273            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13274        }
13275
13276        protected boolean isEphemeral() {
13277            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13278        }
13279
13280        UserHandle getUser() {
13281            return user;
13282        }
13283    }
13284
13285    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13286        if (!allCodePaths.isEmpty()) {
13287            if (instructionSets == null) {
13288                throw new IllegalStateException("instructionSet == null");
13289            }
13290            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13291            for (String codePath : allCodePaths) {
13292                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13293                    try {
13294                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13295                    } catch (InstallerException ignored) {
13296                    }
13297                }
13298            }
13299        }
13300    }
13301
13302    /**
13303     * Logic to handle installation of non-ASEC applications, including copying
13304     * and renaming logic.
13305     */
13306    class FileInstallArgs extends InstallArgs {
13307        private File codeFile;
13308        private File resourceFile;
13309
13310        // Example topology:
13311        // /data/app/com.example/base.apk
13312        // /data/app/com.example/split_foo.apk
13313        // /data/app/com.example/lib/arm/libfoo.so
13314        // /data/app/com.example/lib/arm64/libfoo.so
13315        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13316
13317        /** New install */
13318        FileInstallArgs(InstallParams params) {
13319            super(params.origin, params.move, params.observer, params.installFlags,
13320                    params.installerPackageName, params.volumeUuid,
13321                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13322                    params.grantedRuntimePermissions,
13323                    params.traceMethod, params.traceCookie, params.certificates);
13324            if (isFwdLocked()) {
13325                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13326            }
13327        }
13328
13329        /** Existing install */
13330        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13331            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13332                    null, null, null, 0, null /*certificates*/);
13333            this.codeFile = (codePath != null) ? new File(codePath) : null;
13334            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13335        }
13336
13337        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13338            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13339            try {
13340                return doCopyApk(imcs, temp);
13341            } finally {
13342                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13343            }
13344        }
13345
13346        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13347            if (origin.staged) {
13348                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13349                codeFile = origin.file;
13350                resourceFile = origin.file;
13351                return PackageManager.INSTALL_SUCCEEDED;
13352            }
13353
13354            try {
13355                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13356                final File tempDir =
13357                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13358                codeFile = tempDir;
13359                resourceFile = tempDir;
13360            } catch (IOException e) {
13361                Slog.w(TAG, "Failed to create copy file: " + e);
13362                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13363            }
13364
13365            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13366                @Override
13367                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13368                    if (!FileUtils.isValidExtFilename(name)) {
13369                        throw new IllegalArgumentException("Invalid filename: " + name);
13370                    }
13371                    try {
13372                        final File file = new File(codeFile, name);
13373                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13374                                O_RDWR | O_CREAT, 0644);
13375                        Os.chmod(file.getAbsolutePath(), 0644);
13376                        return new ParcelFileDescriptor(fd);
13377                    } catch (ErrnoException e) {
13378                        throw new RemoteException("Failed to open: " + e.getMessage());
13379                    }
13380                }
13381            };
13382
13383            int ret = PackageManager.INSTALL_SUCCEEDED;
13384            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13385            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13386                Slog.e(TAG, "Failed to copy package");
13387                return ret;
13388            }
13389
13390            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13391            NativeLibraryHelper.Handle handle = null;
13392            try {
13393                handle = NativeLibraryHelper.Handle.create(codeFile);
13394                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13395                        abiOverride);
13396            } catch (IOException e) {
13397                Slog.e(TAG, "Copying native libraries failed", e);
13398                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13399            } finally {
13400                IoUtils.closeQuietly(handle);
13401            }
13402
13403            return ret;
13404        }
13405
13406        int doPreInstall(int status) {
13407            if (status != PackageManager.INSTALL_SUCCEEDED) {
13408                cleanUp();
13409            }
13410            return status;
13411        }
13412
13413        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13414            if (status != PackageManager.INSTALL_SUCCEEDED) {
13415                cleanUp();
13416                return false;
13417            }
13418
13419            final File targetDir = codeFile.getParentFile();
13420            final File beforeCodeFile = codeFile;
13421            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13422
13423            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13424            try {
13425                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13426            } catch (ErrnoException e) {
13427                Slog.w(TAG, "Failed to rename", e);
13428                return false;
13429            }
13430
13431            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13432                Slog.w(TAG, "Failed to restorecon");
13433                return false;
13434            }
13435
13436            // Reflect the rename internally
13437            codeFile = afterCodeFile;
13438            resourceFile = afterCodeFile;
13439
13440            // Reflect the rename in scanned details
13441            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13442            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13443                    afterCodeFile, pkg.baseCodePath));
13444            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13445                    afterCodeFile, pkg.splitCodePaths));
13446
13447            // Reflect the rename in app info
13448            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13449            pkg.setApplicationInfoCodePath(pkg.codePath);
13450            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13451            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13452            pkg.setApplicationInfoResourcePath(pkg.codePath);
13453            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13454            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13455
13456            return true;
13457        }
13458
13459        int doPostInstall(int status, int uid) {
13460            if (status != PackageManager.INSTALL_SUCCEEDED) {
13461                cleanUp();
13462            }
13463            return status;
13464        }
13465
13466        @Override
13467        String getCodePath() {
13468            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13469        }
13470
13471        @Override
13472        String getResourcePath() {
13473            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13474        }
13475
13476        private boolean cleanUp() {
13477            if (codeFile == null || !codeFile.exists()) {
13478                return false;
13479            }
13480
13481            removeCodePathLI(codeFile);
13482
13483            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13484                resourceFile.delete();
13485            }
13486
13487            return true;
13488        }
13489
13490        void cleanUpResourcesLI() {
13491            // Try enumerating all code paths before deleting
13492            List<String> allCodePaths = Collections.EMPTY_LIST;
13493            if (codeFile != null && codeFile.exists()) {
13494                try {
13495                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13496                    allCodePaths = pkg.getAllCodePaths();
13497                } catch (PackageParserException e) {
13498                    // Ignored; we tried our best
13499                }
13500            }
13501
13502            cleanUp();
13503            removeDexFiles(allCodePaths, instructionSets);
13504        }
13505
13506        boolean doPostDeleteLI(boolean delete) {
13507            // XXX err, shouldn't we respect the delete flag?
13508            cleanUpResourcesLI();
13509            return true;
13510        }
13511    }
13512
13513    private boolean isAsecExternal(String cid) {
13514        final String asecPath = PackageHelper.getSdFilesystem(cid);
13515        return !asecPath.startsWith(mAsecInternalPath);
13516    }
13517
13518    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13519            PackageManagerException {
13520        if (copyRet < 0) {
13521            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13522                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13523                throw new PackageManagerException(copyRet, message);
13524            }
13525        }
13526    }
13527
13528    /**
13529     * Extract the MountService "container ID" from the full code path of an
13530     * .apk.
13531     */
13532    static String cidFromCodePath(String fullCodePath) {
13533        int eidx = fullCodePath.lastIndexOf("/");
13534        String subStr1 = fullCodePath.substring(0, eidx);
13535        int sidx = subStr1.lastIndexOf("/");
13536        return subStr1.substring(sidx+1, eidx);
13537    }
13538
13539    /**
13540     * Logic to handle installation of ASEC applications, including copying and
13541     * renaming logic.
13542     */
13543    class AsecInstallArgs extends InstallArgs {
13544        static final String RES_FILE_NAME = "pkg.apk";
13545        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13546
13547        String cid;
13548        String packagePath;
13549        String resourcePath;
13550
13551        /** New install */
13552        AsecInstallArgs(InstallParams params) {
13553            super(params.origin, params.move, params.observer, params.installFlags,
13554                    params.installerPackageName, params.volumeUuid,
13555                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13556                    params.grantedRuntimePermissions,
13557                    params.traceMethod, params.traceCookie, params.certificates);
13558        }
13559
13560        /** Existing install */
13561        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13562                        boolean isExternal, boolean isForwardLocked) {
13563            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13564              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13565                    instructionSets, null, null, null, 0, null /*certificates*/);
13566            // Hackily pretend we're still looking at a full code path
13567            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13568                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13569            }
13570
13571            // Extract cid from fullCodePath
13572            int eidx = fullCodePath.lastIndexOf("/");
13573            String subStr1 = fullCodePath.substring(0, eidx);
13574            int sidx = subStr1.lastIndexOf("/");
13575            cid = subStr1.substring(sidx+1, eidx);
13576            setMountPath(subStr1);
13577        }
13578
13579        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13580            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13581              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13582                    instructionSets, null, null, null, 0, null /*certificates*/);
13583            this.cid = cid;
13584            setMountPath(PackageHelper.getSdDir(cid));
13585        }
13586
13587        void createCopyFile() {
13588            cid = mInstallerService.allocateExternalStageCidLegacy();
13589        }
13590
13591        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13592            if (origin.staged && origin.cid != null) {
13593                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13594                cid = origin.cid;
13595                setMountPath(PackageHelper.getSdDir(cid));
13596                return PackageManager.INSTALL_SUCCEEDED;
13597            }
13598
13599            if (temp) {
13600                createCopyFile();
13601            } else {
13602                /*
13603                 * Pre-emptively destroy the container since it's destroyed if
13604                 * copying fails due to it existing anyway.
13605                 */
13606                PackageHelper.destroySdDir(cid);
13607            }
13608
13609            final String newMountPath = imcs.copyPackageToContainer(
13610                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13611                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13612
13613            if (newMountPath != null) {
13614                setMountPath(newMountPath);
13615                return PackageManager.INSTALL_SUCCEEDED;
13616            } else {
13617                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13618            }
13619        }
13620
13621        @Override
13622        String getCodePath() {
13623            return packagePath;
13624        }
13625
13626        @Override
13627        String getResourcePath() {
13628            return resourcePath;
13629        }
13630
13631        int doPreInstall(int status) {
13632            if (status != PackageManager.INSTALL_SUCCEEDED) {
13633                // Destroy container
13634                PackageHelper.destroySdDir(cid);
13635            } else {
13636                boolean mounted = PackageHelper.isContainerMounted(cid);
13637                if (!mounted) {
13638                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13639                            Process.SYSTEM_UID);
13640                    if (newMountPath != null) {
13641                        setMountPath(newMountPath);
13642                    } else {
13643                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13644                    }
13645                }
13646            }
13647            return status;
13648        }
13649
13650        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13651            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13652            String newMountPath = null;
13653            if (PackageHelper.isContainerMounted(cid)) {
13654                // Unmount the container
13655                if (!PackageHelper.unMountSdDir(cid)) {
13656                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13657                    return false;
13658                }
13659            }
13660            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13661                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13662                        " which might be stale. Will try to clean up.");
13663                // Clean up the stale container and proceed to recreate.
13664                if (!PackageHelper.destroySdDir(newCacheId)) {
13665                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13666                    return false;
13667                }
13668                // Successfully cleaned up stale container. Try to rename again.
13669                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13670                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13671                            + " inspite of cleaning it up.");
13672                    return false;
13673                }
13674            }
13675            if (!PackageHelper.isContainerMounted(newCacheId)) {
13676                Slog.w(TAG, "Mounting container " + newCacheId);
13677                newMountPath = PackageHelper.mountSdDir(newCacheId,
13678                        getEncryptKey(), Process.SYSTEM_UID);
13679            } else {
13680                newMountPath = PackageHelper.getSdDir(newCacheId);
13681            }
13682            if (newMountPath == null) {
13683                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13684                return false;
13685            }
13686            Log.i(TAG, "Succesfully renamed " + cid +
13687                    " to " + newCacheId +
13688                    " at new path: " + newMountPath);
13689            cid = newCacheId;
13690
13691            final File beforeCodeFile = new File(packagePath);
13692            setMountPath(newMountPath);
13693            final File afterCodeFile = new File(packagePath);
13694
13695            // Reflect the rename in scanned details
13696            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13697            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13698                    afterCodeFile, pkg.baseCodePath));
13699            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13700                    afterCodeFile, pkg.splitCodePaths));
13701
13702            // Reflect the rename in app info
13703            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13704            pkg.setApplicationInfoCodePath(pkg.codePath);
13705            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13706            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13707            pkg.setApplicationInfoResourcePath(pkg.codePath);
13708            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13709            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13710
13711            return true;
13712        }
13713
13714        private void setMountPath(String mountPath) {
13715            final File mountFile = new File(mountPath);
13716
13717            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13718            if (monolithicFile.exists()) {
13719                packagePath = monolithicFile.getAbsolutePath();
13720                if (isFwdLocked()) {
13721                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13722                } else {
13723                    resourcePath = packagePath;
13724                }
13725            } else {
13726                packagePath = mountFile.getAbsolutePath();
13727                resourcePath = packagePath;
13728            }
13729        }
13730
13731        int doPostInstall(int status, int uid) {
13732            if (status != PackageManager.INSTALL_SUCCEEDED) {
13733                cleanUp();
13734            } else {
13735                final int groupOwner;
13736                final String protectedFile;
13737                if (isFwdLocked()) {
13738                    groupOwner = UserHandle.getSharedAppGid(uid);
13739                    protectedFile = RES_FILE_NAME;
13740                } else {
13741                    groupOwner = -1;
13742                    protectedFile = null;
13743                }
13744
13745                if (uid < Process.FIRST_APPLICATION_UID
13746                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13747                    Slog.e(TAG, "Failed to finalize " + cid);
13748                    PackageHelper.destroySdDir(cid);
13749                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13750                }
13751
13752                boolean mounted = PackageHelper.isContainerMounted(cid);
13753                if (!mounted) {
13754                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13755                }
13756            }
13757            return status;
13758        }
13759
13760        private void cleanUp() {
13761            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13762
13763            // Destroy secure container
13764            PackageHelper.destroySdDir(cid);
13765        }
13766
13767        private List<String> getAllCodePaths() {
13768            final File codeFile = new File(getCodePath());
13769            if (codeFile != null && codeFile.exists()) {
13770                try {
13771                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13772                    return pkg.getAllCodePaths();
13773                } catch (PackageParserException e) {
13774                    // Ignored; we tried our best
13775                }
13776            }
13777            return Collections.EMPTY_LIST;
13778        }
13779
13780        void cleanUpResourcesLI() {
13781            // Enumerate all code paths before deleting
13782            cleanUpResourcesLI(getAllCodePaths());
13783        }
13784
13785        private void cleanUpResourcesLI(List<String> allCodePaths) {
13786            cleanUp();
13787            removeDexFiles(allCodePaths, instructionSets);
13788        }
13789
13790        String getPackageName() {
13791            return getAsecPackageName(cid);
13792        }
13793
13794        boolean doPostDeleteLI(boolean delete) {
13795            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13796            final List<String> allCodePaths = getAllCodePaths();
13797            boolean mounted = PackageHelper.isContainerMounted(cid);
13798            if (mounted) {
13799                // Unmount first
13800                if (PackageHelper.unMountSdDir(cid)) {
13801                    mounted = false;
13802                }
13803            }
13804            if (!mounted && delete) {
13805                cleanUpResourcesLI(allCodePaths);
13806            }
13807            return !mounted;
13808        }
13809
13810        @Override
13811        int doPreCopy() {
13812            if (isFwdLocked()) {
13813                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13814                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13815                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13816                }
13817            }
13818
13819            return PackageManager.INSTALL_SUCCEEDED;
13820        }
13821
13822        @Override
13823        int doPostCopy(int uid) {
13824            if (isFwdLocked()) {
13825                if (uid < Process.FIRST_APPLICATION_UID
13826                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13827                                RES_FILE_NAME)) {
13828                    Slog.e(TAG, "Failed to finalize " + cid);
13829                    PackageHelper.destroySdDir(cid);
13830                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13831                }
13832            }
13833
13834            return PackageManager.INSTALL_SUCCEEDED;
13835        }
13836    }
13837
13838    /**
13839     * Logic to handle movement of existing installed applications.
13840     */
13841    class MoveInstallArgs extends InstallArgs {
13842        private File codeFile;
13843        private File resourceFile;
13844
13845        /** New install */
13846        MoveInstallArgs(InstallParams params) {
13847            super(params.origin, params.move, params.observer, params.installFlags,
13848                    params.installerPackageName, params.volumeUuid,
13849                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13850                    params.grantedRuntimePermissions,
13851                    params.traceMethod, params.traceCookie, params.certificates);
13852        }
13853
13854        int copyApk(IMediaContainerService imcs, boolean temp) {
13855            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13856                    + move.fromUuid + " to " + move.toUuid);
13857            synchronized (mInstaller) {
13858                try {
13859                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13860                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13861                } catch (InstallerException e) {
13862                    Slog.w(TAG, "Failed to move app", e);
13863                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13864                }
13865            }
13866
13867            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13868            resourceFile = codeFile;
13869            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13870
13871            return PackageManager.INSTALL_SUCCEEDED;
13872        }
13873
13874        int doPreInstall(int status) {
13875            if (status != PackageManager.INSTALL_SUCCEEDED) {
13876                cleanUp(move.toUuid);
13877            }
13878            return status;
13879        }
13880
13881        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13882            if (status != PackageManager.INSTALL_SUCCEEDED) {
13883                cleanUp(move.toUuid);
13884                return false;
13885            }
13886
13887            // Reflect the move in app info
13888            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13889            pkg.setApplicationInfoCodePath(pkg.codePath);
13890            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13891            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13892            pkg.setApplicationInfoResourcePath(pkg.codePath);
13893            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13894            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13895
13896            return true;
13897        }
13898
13899        int doPostInstall(int status, int uid) {
13900            if (status == PackageManager.INSTALL_SUCCEEDED) {
13901                cleanUp(move.fromUuid);
13902            } else {
13903                cleanUp(move.toUuid);
13904            }
13905            return status;
13906        }
13907
13908        @Override
13909        String getCodePath() {
13910            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13911        }
13912
13913        @Override
13914        String getResourcePath() {
13915            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13916        }
13917
13918        private boolean cleanUp(String volumeUuid) {
13919            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13920                    move.dataAppName);
13921            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13922            final int[] userIds = sUserManager.getUserIds();
13923            synchronized (mInstallLock) {
13924                // Clean up both app data and code
13925                // All package moves are frozen until finished
13926                for (int userId : userIds) {
13927                    try {
13928                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13929                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13930                    } catch (InstallerException e) {
13931                        Slog.w(TAG, String.valueOf(e));
13932                    }
13933                }
13934                removeCodePathLI(codeFile);
13935            }
13936            return true;
13937        }
13938
13939        void cleanUpResourcesLI() {
13940            throw new UnsupportedOperationException();
13941        }
13942
13943        boolean doPostDeleteLI(boolean delete) {
13944            throw new UnsupportedOperationException();
13945        }
13946    }
13947
13948    static String getAsecPackageName(String packageCid) {
13949        int idx = packageCid.lastIndexOf("-");
13950        if (idx == -1) {
13951            return packageCid;
13952        }
13953        return packageCid.substring(0, idx);
13954    }
13955
13956    // Utility method used to create code paths based on package name and available index.
13957    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13958        String idxStr = "";
13959        int idx = 1;
13960        // Fall back to default value of idx=1 if prefix is not
13961        // part of oldCodePath
13962        if (oldCodePath != null) {
13963            String subStr = oldCodePath;
13964            // Drop the suffix right away
13965            if (suffix != null && subStr.endsWith(suffix)) {
13966                subStr = subStr.substring(0, subStr.length() - suffix.length());
13967            }
13968            // If oldCodePath already contains prefix find out the
13969            // ending index to either increment or decrement.
13970            int sidx = subStr.lastIndexOf(prefix);
13971            if (sidx != -1) {
13972                subStr = subStr.substring(sidx + prefix.length());
13973                if (subStr != null) {
13974                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13975                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13976                    }
13977                    try {
13978                        idx = Integer.parseInt(subStr);
13979                        if (idx <= 1) {
13980                            idx++;
13981                        } else {
13982                            idx--;
13983                        }
13984                    } catch(NumberFormatException e) {
13985                    }
13986                }
13987            }
13988        }
13989        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13990        return prefix + idxStr;
13991    }
13992
13993    private File getNextCodePath(File targetDir, String packageName) {
13994        int suffix = 1;
13995        File result;
13996        do {
13997            result = new File(targetDir, packageName + "-" + suffix);
13998            suffix++;
13999        } while (result.exists());
14000        return result;
14001    }
14002
14003    // Utility method that returns the relative package path with respect
14004    // to the installation directory. Like say for /data/data/com.test-1.apk
14005    // string com.test-1 is returned.
14006    static String deriveCodePathName(String codePath) {
14007        if (codePath == null) {
14008            return null;
14009        }
14010        final File codeFile = new File(codePath);
14011        final String name = codeFile.getName();
14012        if (codeFile.isDirectory()) {
14013            return name;
14014        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14015            final int lastDot = name.lastIndexOf('.');
14016            return name.substring(0, lastDot);
14017        } else {
14018            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14019            return null;
14020        }
14021    }
14022
14023    static class PackageInstalledInfo {
14024        String name;
14025        int uid;
14026        // The set of users that originally had this package installed.
14027        int[] origUsers;
14028        // The set of users that now have this package installed.
14029        int[] newUsers;
14030        PackageParser.Package pkg;
14031        int returnCode;
14032        String returnMsg;
14033        PackageRemovedInfo removedInfo;
14034        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14035
14036        public void setError(int code, String msg) {
14037            setReturnCode(code);
14038            setReturnMessage(msg);
14039            Slog.w(TAG, msg);
14040        }
14041
14042        public void setError(String msg, PackageParserException e) {
14043            setReturnCode(e.error);
14044            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14045            Slog.w(TAG, msg, e);
14046        }
14047
14048        public void setError(String msg, PackageManagerException e) {
14049            returnCode = e.error;
14050            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14051            Slog.w(TAG, msg, e);
14052        }
14053
14054        public void setReturnCode(int returnCode) {
14055            this.returnCode = returnCode;
14056            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14057            for (int i = 0; i < childCount; i++) {
14058                addedChildPackages.valueAt(i).returnCode = returnCode;
14059            }
14060        }
14061
14062        private void setReturnMessage(String returnMsg) {
14063            this.returnMsg = returnMsg;
14064            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14065            for (int i = 0; i < childCount; i++) {
14066                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14067            }
14068        }
14069
14070        // In some error cases we want to convey more info back to the observer
14071        String origPackage;
14072        String origPermission;
14073    }
14074
14075    /*
14076     * Install a non-existing package.
14077     */
14078    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14079            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14080            PackageInstalledInfo res) {
14081        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14082
14083        // Remember this for later, in case we need to rollback this install
14084        String pkgName = pkg.packageName;
14085
14086        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14087
14088        synchronized(mPackages) {
14089            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14090                // A package with the same name is already installed, though
14091                // it has been renamed to an older name.  The package we
14092                // are trying to install should be installed as an update to
14093                // the existing one, but that has not been requested, so bail.
14094                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14095                        + " without first uninstalling package running as "
14096                        + mSettings.mRenamedPackages.get(pkgName));
14097                return;
14098            }
14099            if (mPackages.containsKey(pkgName)) {
14100                // Don't allow installation over an existing package with the same name.
14101                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14102                        + " without first uninstalling.");
14103                return;
14104            }
14105        }
14106
14107        try {
14108            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14109                    System.currentTimeMillis(), user);
14110
14111            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14112
14113            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14114                prepareAppDataAfterInstallLIF(newPackage);
14115
14116            } else {
14117                // Remove package from internal structures, but keep around any
14118                // data that might have already existed
14119                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14120                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14121            }
14122        } catch (PackageManagerException e) {
14123            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14124        }
14125
14126        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14127    }
14128
14129    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14130        // Can't rotate keys during boot or if sharedUser.
14131        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14132                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14133            return false;
14134        }
14135        // app is using upgradeKeySets; make sure all are valid
14136        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14137        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14138        for (int i = 0; i < upgradeKeySets.length; i++) {
14139            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14140                Slog.wtf(TAG, "Package "
14141                         + (oldPs.name != null ? oldPs.name : "<null>")
14142                         + " contains upgrade-key-set reference to unknown key-set: "
14143                         + upgradeKeySets[i]
14144                         + " reverting to signatures check.");
14145                return false;
14146            }
14147        }
14148        return true;
14149    }
14150
14151    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14152        // Upgrade keysets are being used.  Determine if new package has a superset of the
14153        // required keys.
14154        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14155        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14156        for (int i = 0; i < upgradeKeySets.length; i++) {
14157            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14158            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14159                return true;
14160            }
14161        }
14162        return false;
14163    }
14164
14165    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14166        try (DigestInputStream digestStream =
14167                new DigestInputStream(new FileInputStream(file), digest)) {
14168            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14169        }
14170    }
14171
14172    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14173            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14174        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14175
14176        final PackageParser.Package oldPackage;
14177        final String pkgName = pkg.packageName;
14178        final int[] allUsers;
14179        final int[] installedUsers;
14180
14181        synchronized(mPackages) {
14182            oldPackage = mPackages.get(pkgName);
14183            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14184
14185            // don't allow upgrade to target a release SDK from a pre-release SDK
14186            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14187                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14188            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14189                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14190            if (oldTargetsPreRelease
14191                    && !newTargetsPreRelease
14192                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14193                Slog.w(TAG, "Can't install package targeting released sdk");
14194                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14195                return;
14196            }
14197
14198            // don't allow an upgrade from full to ephemeral
14199            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14200            if (isEphemeral && !oldIsEphemeral) {
14201                // can't downgrade from full to ephemeral
14202                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14203                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14204                return;
14205            }
14206
14207            // verify signatures are valid
14208            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14209            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14210                if (!checkUpgradeKeySetLP(ps, pkg)) {
14211                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14212                            "New package not signed by keys specified by upgrade-keysets: "
14213                                    + pkgName);
14214                    return;
14215                }
14216            } else {
14217                // default to original signature matching
14218                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14219                        != PackageManager.SIGNATURE_MATCH) {
14220                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14221                            "New package has a different signature: " + pkgName);
14222                    return;
14223                }
14224            }
14225
14226            // don't allow a system upgrade unless the upgrade hash matches
14227            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14228                byte[] digestBytes = null;
14229                try {
14230                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14231                    updateDigest(digest, new File(pkg.baseCodePath));
14232                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14233                        for (String path : pkg.splitCodePaths) {
14234                            updateDigest(digest, new File(path));
14235                        }
14236                    }
14237                    digestBytes = digest.digest();
14238                } catch (NoSuchAlgorithmException | IOException e) {
14239                    res.setError(INSTALL_FAILED_INVALID_APK,
14240                            "Could not compute hash: " + pkgName);
14241                    return;
14242                }
14243                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14244                    res.setError(INSTALL_FAILED_INVALID_APK,
14245                            "New package fails restrict-update check: " + pkgName);
14246                    return;
14247                }
14248                // retain upgrade restriction
14249                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14250            }
14251
14252            // Check for shared user id changes
14253            String invalidPackageName =
14254                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14255            if (invalidPackageName != null) {
14256                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14257                        "Package " + invalidPackageName + " tried to change user "
14258                                + oldPackage.mSharedUserId);
14259                return;
14260            }
14261
14262            // In case of rollback, remember per-user/profile install state
14263            allUsers = sUserManager.getUserIds();
14264            installedUsers = ps.queryInstalledUsers(allUsers, true);
14265        }
14266
14267        // Update what is removed
14268        res.removedInfo = new PackageRemovedInfo();
14269        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14270        res.removedInfo.removedPackage = oldPackage.packageName;
14271        res.removedInfo.isUpdate = true;
14272        res.removedInfo.origUsers = installedUsers;
14273        final int childCount = (oldPackage.childPackages != null)
14274                ? oldPackage.childPackages.size() : 0;
14275        for (int i = 0; i < childCount; i++) {
14276            boolean childPackageUpdated = false;
14277            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14278            if (res.addedChildPackages != null) {
14279                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14280                if (childRes != null) {
14281                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14282                    childRes.removedInfo.removedPackage = childPkg.packageName;
14283                    childRes.removedInfo.isUpdate = true;
14284                    childPackageUpdated = true;
14285                }
14286            }
14287            if (!childPackageUpdated) {
14288                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14289                childRemovedRes.removedPackage = childPkg.packageName;
14290                childRemovedRes.isUpdate = false;
14291                childRemovedRes.dataRemoved = true;
14292                synchronized (mPackages) {
14293                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14294                    if (childPs != null) {
14295                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14296                    }
14297                }
14298                if (res.removedInfo.removedChildPackages == null) {
14299                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14300                }
14301                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14302            }
14303        }
14304
14305        boolean sysPkg = (isSystemApp(oldPackage));
14306        if (sysPkg) {
14307            // Set the system/privileged flags as needed
14308            final boolean privileged =
14309                    (oldPackage.applicationInfo.privateFlags
14310                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14311            final int systemPolicyFlags = policyFlags
14312                    | PackageParser.PARSE_IS_SYSTEM
14313                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14314
14315            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14316                    user, allUsers, installerPackageName, res);
14317        } else {
14318            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14319                    user, allUsers, installerPackageName, res);
14320        }
14321    }
14322
14323    public List<String> getPreviousCodePaths(String packageName) {
14324        final PackageSetting ps = mSettings.mPackages.get(packageName);
14325        final List<String> result = new ArrayList<String>();
14326        if (ps != null && ps.oldCodePaths != null) {
14327            result.addAll(ps.oldCodePaths);
14328        }
14329        return result;
14330    }
14331
14332    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14333            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14334            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14335        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14336                + deletedPackage);
14337
14338        String pkgName = deletedPackage.packageName;
14339        boolean deletedPkg = true;
14340        boolean addedPkg = false;
14341        boolean updatedSettings = false;
14342        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14343        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14344                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14345
14346        final long origUpdateTime = (pkg.mExtras != null)
14347                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14348
14349        // First delete the existing package while retaining the data directory
14350        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14351                res.removedInfo, true, pkg)) {
14352            // If the existing package wasn't successfully deleted
14353            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14354            deletedPkg = false;
14355        } else {
14356            // Successfully deleted the old package; proceed with replace.
14357
14358            // If deleted package lived in a container, give users a chance to
14359            // relinquish resources before killing.
14360            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14361                if (DEBUG_INSTALL) {
14362                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14363                }
14364                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14365                final ArrayList<String> pkgList = new ArrayList<String>(1);
14366                pkgList.add(deletedPackage.applicationInfo.packageName);
14367                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14368            }
14369
14370            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14371                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14372            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14373
14374            try {
14375                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14376                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14377                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14378
14379                // Update the in-memory copy of the previous code paths.
14380                PackageSetting ps = mSettings.mPackages.get(pkgName);
14381                if (!killApp) {
14382                    if (ps.oldCodePaths == null) {
14383                        ps.oldCodePaths = new ArraySet<>();
14384                    }
14385                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14386                    if (deletedPackage.splitCodePaths != null) {
14387                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14388                    }
14389                } else {
14390                    ps.oldCodePaths = null;
14391                }
14392                if (ps.childPackageNames != null) {
14393                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14394                        final String childPkgName = ps.childPackageNames.get(i);
14395                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14396                        childPs.oldCodePaths = ps.oldCodePaths;
14397                    }
14398                }
14399                prepareAppDataAfterInstallLIF(newPackage);
14400                addedPkg = true;
14401            } catch (PackageManagerException e) {
14402                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14403            }
14404        }
14405
14406        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14407            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14408
14409            // Revert all internal state mutations and added folders for the failed install
14410            if (addedPkg) {
14411                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14412                        res.removedInfo, true, null);
14413            }
14414
14415            // Restore the old package
14416            if (deletedPkg) {
14417                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14418                File restoreFile = new File(deletedPackage.codePath);
14419                // Parse old package
14420                boolean oldExternal = isExternal(deletedPackage);
14421                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14422                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14423                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14424                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14425                try {
14426                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14427                            null);
14428                } catch (PackageManagerException e) {
14429                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14430                            + e.getMessage());
14431                    return;
14432                }
14433
14434                synchronized (mPackages) {
14435                    // Ensure the installer package name up to date
14436                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14437
14438                    // Update permissions for restored package
14439                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14440
14441                    mSettings.writeLPr();
14442                }
14443
14444                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14445            }
14446        } else {
14447            synchronized (mPackages) {
14448                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14449                if (ps != null) {
14450                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14451                    if (res.removedInfo.removedChildPackages != null) {
14452                        final int childCount = res.removedInfo.removedChildPackages.size();
14453                        // Iterate in reverse as we may modify the collection
14454                        for (int i = childCount - 1; i >= 0; i--) {
14455                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14456                            if (res.addedChildPackages.containsKey(childPackageName)) {
14457                                res.removedInfo.removedChildPackages.removeAt(i);
14458                            } else {
14459                                PackageRemovedInfo childInfo = res.removedInfo
14460                                        .removedChildPackages.valueAt(i);
14461                                childInfo.removedForAllUsers = mPackages.get(
14462                                        childInfo.removedPackage) == null;
14463                            }
14464                        }
14465                    }
14466                }
14467            }
14468        }
14469    }
14470
14471    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14472            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14473            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14474        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14475                + ", old=" + deletedPackage);
14476
14477        final boolean disabledSystem;
14478
14479        // Remove existing system package
14480        removePackageLI(deletedPackage, true);
14481
14482        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14483        if (!disabledSystem) {
14484            // We didn't need to disable the .apk as a current system package,
14485            // which means we are replacing another update that is already
14486            // installed.  We need to make sure to delete the older one's .apk.
14487            res.removedInfo.args = createInstallArgsForExisting(0,
14488                    deletedPackage.applicationInfo.getCodePath(),
14489                    deletedPackage.applicationInfo.getResourcePath(),
14490                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14491        } else {
14492            res.removedInfo.args = null;
14493        }
14494
14495        // Successfully disabled the old package. Now proceed with re-installation
14496        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14497                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14498        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14499
14500        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14501        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14502                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14503
14504        PackageParser.Package newPackage = null;
14505        try {
14506            // Add the package to the internal data structures
14507            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14508
14509            // Set the update and install times
14510            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14511            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14512                    System.currentTimeMillis());
14513
14514            // Update the package dynamic state if succeeded
14515            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14516                // Now that the install succeeded make sure we remove data
14517                // directories for any child package the update removed.
14518                final int deletedChildCount = (deletedPackage.childPackages != null)
14519                        ? deletedPackage.childPackages.size() : 0;
14520                final int newChildCount = (newPackage.childPackages != null)
14521                        ? newPackage.childPackages.size() : 0;
14522                for (int i = 0; i < deletedChildCount; i++) {
14523                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14524                    boolean childPackageDeleted = true;
14525                    for (int j = 0; j < newChildCount; j++) {
14526                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14527                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14528                            childPackageDeleted = false;
14529                            break;
14530                        }
14531                    }
14532                    if (childPackageDeleted) {
14533                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14534                                deletedChildPkg.packageName);
14535                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14536                            PackageRemovedInfo removedChildRes = res.removedInfo
14537                                    .removedChildPackages.get(deletedChildPkg.packageName);
14538                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14539                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14540                        }
14541                    }
14542                }
14543
14544                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14545                prepareAppDataAfterInstallLIF(newPackage);
14546            }
14547        } catch (PackageManagerException e) {
14548            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14549            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14550        }
14551
14552        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14553            // Re installation failed. Restore old information
14554            // Remove new pkg information
14555            if (newPackage != null) {
14556                removeInstalledPackageLI(newPackage, true);
14557            }
14558            // Add back the old system package
14559            try {
14560                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14561            } catch (PackageManagerException e) {
14562                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14563            }
14564
14565            synchronized (mPackages) {
14566                if (disabledSystem) {
14567                    enableSystemPackageLPw(deletedPackage);
14568                }
14569
14570                // Ensure the installer package name up to date
14571                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14572
14573                // Update permissions for restored package
14574                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14575
14576                mSettings.writeLPr();
14577            }
14578
14579            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14580                    + " after failed upgrade");
14581        }
14582    }
14583
14584    /**
14585     * Checks whether the parent or any of the child packages have a change shared
14586     * user. For a package to be a valid update the shred users of the parent and
14587     * the children should match. We may later support changing child shared users.
14588     * @param oldPkg The updated package.
14589     * @param newPkg The update package.
14590     * @return The shared user that change between the versions.
14591     */
14592    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14593            PackageParser.Package newPkg) {
14594        // Check parent shared user
14595        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14596            return newPkg.packageName;
14597        }
14598        // Check child shared users
14599        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14600        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14601        for (int i = 0; i < newChildCount; i++) {
14602            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14603            // If this child was present, did it have the same shared user?
14604            for (int j = 0; j < oldChildCount; j++) {
14605                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14606                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14607                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14608                    return newChildPkg.packageName;
14609                }
14610            }
14611        }
14612        return null;
14613    }
14614
14615    private void removeNativeBinariesLI(PackageSetting ps) {
14616        // Remove the lib path for the parent package
14617        if (ps != null) {
14618            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14619            // Remove the lib path for the child packages
14620            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14621            for (int i = 0; i < childCount; i++) {
14622                PackageSetting childPs = null;
14623                synchronized (mPackages) {
14624                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14625                }
14626                if (childPs != null) {
14627                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14628                            .legacyNativeLibraryPathString);
14629                }
14630            }
14631        }
14632    }
14633
14634    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14635        // Enable the parent package
14636        mSettings.enableSystemPackageLPw(pkg.packageName);
14637        // Enable the child packages
14638        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14639        for (int i = 0; i < childCount; i++) {
14640            PackageParser.Package childPkg = pkg.childPackages.get(i);
14641            mSettings.enableSystemPackageLPw(childPkg.packageName);
14642        }
14643    }
14644
14645    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14646            PackageParser.Package newPkg) {
14647        // Disable the parent package (parent always replaced)
14648        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14649        // Disable the child packages
14650        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14651        for (int i = 0; i < childCount; i++) {
14652            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14653            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14654            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14655        }
14656        return disabled;
14657    }
14658
14659    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14660            String installerPackageName) {
14661        // Enable the parent package
14662        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14663        // Enable the child packages
14664        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14665        for (int i = 0; i < childCount; i++) {
14666            PackageParser.Package childPkg = pkg.childPackages.get(i);
14667            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14668        }
14669    }
14670
14671    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14672        // Collect all used permissions in the UID
14673        ArraySet<String> usedPermissions = new ArraySet<>();
14674        final int packageCount = su.packages.size();
14675        for (int i = 0; i < packageCount; i++) {
14676            PackageSetting ps = su.packages.valueAt(i);
14677            if (ps.pkg == null) {
14678                continue;
14679            }
14680            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14681            for (int j = 0; j < requestedPermCount; j++) {
14682                String permission = ps.pkg.requestedPermissions.get(j);
14683                BasePermission bp = mSettings.mPermissions.get(permission);
14684                if (bp != null) {
14685                    usedPermissions.add(permission);
14686                }
14687            }
14688        }
14689
14690        PermissionsState permissionsState = su.getPermissionsState();
14691        // Prune install permissions
14692        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14693        final int installPermCount = installPermStates.size();
14694        for (int i = installPermCount - 1; i >= 0;  i--) {
14695            PermissionState permissionState = installPermStates.get(i);
14696            if (!usedPermissions.contains(permissionState.getName())) {
14697                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14698                if (bp != null) {
14699                    permissionsState.revokeInstallPermission(bp);
14700                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14701                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14702                }
14703            }
14704        }
14705
14706        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14707
14708        // Prune runtime permissions
14709        for (int userId : allUserIds) {
14710            List<PermissionState> runtimePermStates = permissionsState
14711                    .getRuntimePermissionStates(userId);
14712            final int runtimePermCount = runtimePermStates.size();
14713            for (int i = runtimePermCount - 1; i >= 0; i--) {
14714                PermissionState permissionState = runtimePermStates.get(i);
14715                if (!usedPermissions.contains(permissionState.getName())) {
14716                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14717                    if (bp != null) {
14718                        permissionsState.revokeRuntimePermission(bp, userId);
14719                        permissionsState.updatePermissionFlags(bp, userId,
14720                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14721                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14722                                runtimePermissionChangedUserIds, userId);
14723                    }
14724                }
14725            }
14726        }
14727
14728        return runtimePermissionChangedUserIds;
14729    }
14730
14731    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14732            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14733        // Update the parent package setting
14734        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14735                res, user);
14736        // Update the child packages setting
14737        final int childCount = (newPackage.childPackages != null)
14738                ? newPackage.childPackages.size() : 0;
14739        for (int i = 0; i < childCount; i++) {
14740            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14741            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14742            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14743                    childRes.origUsers, childRes, user);
14744        }
14745    }
14746
14747    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14748            String installerPackageName, int[] allUsers, int[] installedForUsers,
14749            PackageInstalledInfo res, UserHandle user) {
14750        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14751
14752        String pkgName = newPackage.packageName;
14753        synchronized (mPackages) {
14754            //write settings. the installStatus will be incomplete at this stage.
14755            //note that the new package setting would have already been
14756            //added to mPackages. It hasn't been persisted yet.
14757            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14758            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14759            mSettings.writeLPr();
14760            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14761        }
14762
14763        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14764        synchronized (mPackages) {
14765            updatePermissionsLPw(newPackage.packageName, newPackage,
14766                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14767                            ? UPDATE_PERMISSIONS_ALL : 0));
14768            // For system-bundled packages, we assume that installing an upgraded version
14769            // of the package implies that the user actually wants to run that new code,
14770            // so we enable the package.
14771            PackageSetting ps = mSettings.mPackages.get(pkgName);
14772            final int userId = user.getIdentifier();
14773            if (ps != null) {
14774                if (isSystemApp(newPackage)) {
14775                    if (DEBUG_INSTALL) {
14776                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14777                    }
14778                    // Enable system package for requested users
14779                    if (res.origUsers != null) {
14780                        for (int origUserId : res.origUsers) {
14781                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14782                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14783                                        origUserId, installerPackageName);
14784                            }
14785                        }
14786                    }
14787                    // Also convey the prior install/uninstall state
14788                    if (allUsers != null && installedForUsers != null) {
14789                        for (int currentUserId : allUsers) {
14790                            final boolean installed = ArrayUtils.contains(
14791                                    installedForUsers, currentUserId);
14792                            if (DEBUG_INSTALL) {
14793                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14794                            }
14795                            ps.setInstalled(installed, currentUserId);
14796                        }
14797                        // these install state changes will be persisted in the
14798                        // upcoming call to mSettings.writeLPr().
14799                    }
14800                }
14801                // It's implied that when a user requests installation, they want the app to be
14802                // installed and enabled.
14803                if (userId != UserHandle.USER_ALL) {
14804                    ps.setInstalled(true, userId);
14805                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14806                }
14807            }
14808            res.name = pkgName;
14809            res.uid = newPackage.applicationInfo.uid;
14810            res.pkg = newPackage;
14811            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14812            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14813            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14814            //to update install status
14815            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14816            mSettings.writeLPr();
14817            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14818        }
14819
14820        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14821    }
14822
14823    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14824        try {
14825            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14826            installPackageLI(args, res);
14827        } finally {
14828            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14829        }
14830    }
14831
14832    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14833        final int installFlags = args.installFlags;
14834        final String installerPackageName = args.installerPackageName;
14835        final String volumeUuid = args.volumeUuid;
14836        final File tmpPackageFile = new File(args.getCodePath());
14837        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14838        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14839                || (args.volumeUuid != null));
14840        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14841        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14842        boolean replace = false;
14843        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14844        if (args.move != null) {
14845            // moving a complete application; perform an initial scan on the new install location
14846            scanFlags |= SCAN_INITIAL;
14847        }
14848        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14849            scanFlags |= SCAN_DONT_KILL_APP;
14850        }
14851
14852        // Result object to be returned
14853        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14854
14855        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14856
14857        // Sanity check
14858        if (ephemeral && (forwardLocked || onExternal)) {
14859            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14860                    + " external=" + onExternal);
14861            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14862            return;
14863        }
14864
14865        // Retrieve PackageSettings and parse package
14866        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14867                | PackageParser.PARSE_ENFORCE_CODE
14868                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14869                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14870                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14871                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14872        PackageParser pp = new PackageParser();
14873        pp.setSeparateProcesses(mSeparateProcesses);
14874        pp.setDisplayMetrics(mMetrics);
14875
14876        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14877        final PackageParser.Package pkg;
14878        try {
14879            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14880        } catch (PackageParserException e) {
14881            res.setError("Failed parse during installPackageLI", e);
14882            return;
14883        } finally {
14884            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14885        }
14886
14887        // If we are installing a clustered package add results for the children
14888        if (pkg.childPackages != null) {
14889            synchronized (mPackages) {
14890                final int childCount = pkg.childPackages.size();
14891                for (int i = 0; i < childCount; i++) {
14892                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14893                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14894                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14895                    childRes.pkg = childPkg;
14896                    childRes.name = childPkg.packageName;
14897                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14898                    if (childPs != null) {
14899                        childRes.origUsers = childPs.queryInstalledUsers(
14900                                sUserManager.getUserIds(), true);
14901                    }
14902                    if ((mPackages.containsKey(childPkg.packageName))) {
14903                        childRes.removedInfo = new PackageRemovedInfo();
14904                        childRes.removedInfo.removedPackage = childPkg.packageName;
14905                    }
14906                    if (res.addedChildPackages == null) {
14907                        res.addedChildPackages = new ArrayMap<>();
14908                    }
14909                    res.addedChildPackages.put(childPkg.packageName, childRes);
14910                }
14911            }
14912        }
14913
14914        // If package doesn't declare API override, mark that we have an install
14915        // time CPU ABI override.
14916        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14917            pkg.cpuAbiOverride = args.abiOverride;
14918        }
14919
14920        String pkgName = res.name = pkg.packageName;
14921        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14922            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14923                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14924                return;
14925            }
14926        }
14927
14928        try {
14929            // either use what we've been given or parse directly from the APK
14930            if (args.certificates != null) {
14931                try {
14932                    PackageParser.populateCertificates(pkg, args.certificates);
14933                } catch (PackageParserException e) {
14934                    // there was something wrong with the certificates we were given;
14935                    // try to pull them from the APK
14936                    PackageParser.collectCertificates(pkg, parseFlags);
14937                }
14938            } else {
14939                PackageParser.collectCertificates(pkg, parseFlags);
14940            }
14941        } catch (PackageParserException e) {
14942            res.setError("Failed collect during installPackageLI", e);
14943            return;
14944        }
14945
14946        // Get rid of all references to package scan path via parser.
14947        pp = null;
14948        String oldCodePath = null;
14949        boolean systemApp = false;
14950        synchronized (mPackages) {
14951            // Check if installing already existing package
14952            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14953                String oldName = mSettings.mRenamedPackages.get(pkgName);
14954                if (pkg.mOriginalPackages != null
14955                        && pkg.mOriginalPackages.contains(oldName)
14956                        && mPackages.containsKey(oldName)) {
14957                    // This package is derived from an original package,
14958                    // and this device has been updating from that original
14959                    // name.  We must continue using the original name, so
14960                    // rename the new package here.
14961                    pkg.setPackageName(oldName);
14962                    pkgName = pkg.packageName;
14963                    replace = true;
14964                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14965                            + oldName + " pkgName=" + pkgName);
14966                } else if (mPackages.containsKey(pkgName)) {
14967                    // This package, under its official name, already exists
14968                    // on the device; we should replace it.
14969                    replace = true;
14970                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14971                }
14972
14973                // Child packages are installed through the parent package
14974                if (pkg.parentPackage != null) {
14975                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14976                            "Package " + pkg.packageName + " is child of package "
14977                                    + pkg.parentPackage.parentPackage + ". Child packages "
14978                                    + "can be updated only through the parent package.");
14979                    return;
14980                }
14981
14982                if (replace) {
14983                    // Prevent apps opting out from runtime permissions
14984                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14985                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14986                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14987                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14988                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14989                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14990                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14991                                        + " doesn't support runtime permissions but the old"
14992                                        + " target SDK " + oldTargetSdk + " does.");
14993                        return;
14994                    }
14995
14996                    // Prevent installing of child packages
14997                    if (oldPackage.parentPackage != null) {
14998                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14999                                "Package " + pkg.packageName + " is child of package "
15000                                        + oldPackage.parentPackage + ". Child packages "
15001                                        + "can be updated only through the parent package.");
15002                        return;
15003                    }
15004                }
15005            }
15006
15007            PackageSetting ps = mSettings.mPackages.get(pkgName);
15008            if (ps != null) {
15009                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15010
15011                // Quick sanity check that we're signed correctly if updating;
15012                // we'll check this again later when scanning, but we want to
15013                // bail early here before tripping over redefined permissions.
15014                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15015                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15016                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15017                                + pkg.packageName + " upgrade keys do not match the "
15018                                + "previously installed version");
15019                        return;
15020                    }
15021                } else {
15022                    try {
15023                        verifySignaturesLP(ps, pkg);
15024                    } catch (PackageManagerException e) {
15025                        res.setError(e.error, e.getMessage());
15026                        return;
15027                    }
15028                }
15029
15030                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15031                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15032                    systemApp = (ps.pkg.applicationInfo.flags &
15033                            ApplicationInfo.FLAG_SYSTEM) != 0;
15034                }
15035                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15036            }
15037
15038            // Check whether the newly-scanned package wants to define an already-defined perm
15039            int N = pkg.permissions.size();
15040            for (int i = N-1; i >= 0; i--) {
15041                PackageParser.Permission perm = pkg.permissions.get(i);
15042                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15043                if (bp != null) {
15044                    // If the defining package is signed with our cert, it's okay.  This
15045                    // also includes the "updating the same package" case, of course.
15046                    // "updating same package" could also involve key-rotation.
15047                    final boolean sigsOk;
15048                    if (bp.sourcePackage.equals(pkg.packageName)
15049                            && (bp.packageSetting instanceof PackageSetting)
15050                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15051                                    scanFlags))) {
15052                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15053                    } else {
15054                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15055                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15056                    }
15057                    if (!sigsOk) {
15058                        // If the owning package is the system itself, we log but allow
15059                        // install to proceed; we fail the install on all other permission
15060                        // redefinitions.
15061                        if (!bp.sourcePackage.equals("android")) {
15062                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15063                                    + pkg.packageName + " attempting to redeclare permission "
15064                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15065                            res.origPermission = perm.info.name;
15066                            res.origPackage = bp.sourcePackage;
15067                            return;
15068                        } else {
15069                            Slog.w(TAG, "Package " + pkg.packageName
15070                                    + " attempting to redeclare system permission "
15071                                    + perm.info.name + "; ignoring new declaration");
15072                            pkg.permissions.remove(i);
15073                        }
15074                    }
15075                }
15076            }
15077        }
15078
15079        if (systemApp) {
15080            if (onExternal) {
15081                // Abort update; system app can't be replaced with app on sdcard
15082                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15083                        "Cannot install updates to system apps on sdcard");
15084                return;
15085            } else if (ephemeral) {
15086                // Abort update; system app can't be replaced with an ephemeral app
15087                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15088                        "Cannot update a system app with an ephemeral app");
15089                return;
15090            }
15091        }
15092
15093        if (args.move != null) {
15094            // We did an in-place move, so dex is ready to roll
15095            scanFlags |= SCAN_NO_DEX;
15096            scanFlags |= SCAN_MOVE;
15097
15098            synchronized (mPackages) {
15099                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15100                if (ps == null) {
15101                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15102                            "Missing settings for moved package " + pkgName);
15103                }
15104
15105                // We moved the entire application as-is, so bring over the
15106                // previously derived ABI information.
15107                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15108                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15109            }
15110
15111        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15112            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15113            scanFlags |= SCAN_NO_DEX;
15114
15115            try {
15116                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15117                    args.abiOverride : pkg.cpuAbiOverride);
15118                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15119                        true /* extract libs */);
15120            } catch (PackageManagerException pme) {
15121                Slog.e(TAG, "Error deriving application ABI", pme);
15122                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15123                return;
15124            }
15125
15126            // Shared libraries for the package need to be updated.
15127            synchronized (mPackages) {
15128                try {
15129                    updateSharedLibrariesLPw(pkg, null);
15130                } catch (PackageManagerException e) {
15131                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15132                }
15133            }
15134            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15135            // Do not run PackageDexOptimizer through the local performDexOpt
15136            // method because `pkg` is not in `mPackages` yet.
15137            int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15138                    null /* instructionSets */, false /* checkProfiles */,
15139                    getCompilerFilterForReason(REASON_INSTALL));
15140            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15141            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
15142                String msg = "Extracting package failed for " + pkgName;
15143                res.setError(INSTALL_FAILED_DEXOPT, msg);
15144                return;
15145            }
15146
15147            // Notify BackgroundDexOptService that the package has been changed.
15148            // If this is an update of a package which used to fail to compile,
15149            // BDOS will remove it from its blacklist.
15150            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15151        }
15152
15153        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15154            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15155            return;
15156        }
15157
15158        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15159
15160        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15161                "installPackageLI")) {
15162            if (replace) {
15163                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15164                        installerPackageName, res);
15165            } else {
15166                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15167                        args.user, installerPackageName, volumeUuid, res);
15168            }
15169        }
15170        synchronized (mPackages) {
15171            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15172            if (ps != null) {
15173                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15174            }
15175
15176            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15177            for (int i = 0; i < childCount; i++) {
15178                PackageParser.Package childPkg = pkg.childPackages.get(i);
15179                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15180                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15181                if (childPs != null) {
15182                    childRes.newUsers = childPs.queryInstalledUsers(
15183                            sUserManager.getUserIds(), true);
15184                }
15185            }
15186        }
15187    }
15188
15189    private void startIntentFilterVerifications(int userId, boolean replacing,
15190            PackageParser.Package pkg) {
15191        if (mIntentFilterVerifierComponent == null) {
15192            Slog.w(TAG, "No IntentFilter verification will not be done as "
15193                    + "there is no IntentFilterVerifier available!");
15194            return;
15195        }
15196
15197        final int verifierUid = getPackageUid(
15198                mIntentFilterVerifierComponent.getPackageName(),
15199                MATCH_DEBUG_TRIAGED_MISSING,
15200                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15201
15202        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15203        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15204        mHandler.sendMessage(msg);
15205
15206        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15207        for (int i = 0; i < childCount; i++) {
15208            PackageParser.Package childPkg = pkg.childPackages.get(i);
15209            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15210            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15211            mHandler.sendMessage(msg);
15212        }
15213    }
15214
15215    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15216            PackageParser.Package pkg) {
15217        int size = pkg.activities.size();
15218        if (size == 0) {
15219            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15220                    "No activity, so no need to verify any IntentFilter!");
15221            return;
15222        }
15223
15224        final boolean hasDomainURLs = hasDomainURLs(pkg);
15225        if (!hasDomainURLs) {
15226            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15227                    "No domain URLs, so no need to verify any IntentFilter!");
15228            return;
15229        }
15230
15231        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15232                + " if any IntentFilter from the " + size
15233                + " Activities needs verification ...");
15234
15235        int count = 0;
15236        final String packageName = pkg.packageName;
15237
15238        synchronized (mPackages) {
15239            // If this is a new install and we see that we've already run verification for this
15240            // package, we have nothing to do: it means the state was restored from backup.
15241            if (!replacing) {
15242                IntentFilterVerificationInfo ivi =
15243                        mSettings.getIntentFilterVerificationLPr(packageName);
15244                if (ivi != null) {
15245                    if (DEBUG_DOMAIN_VERIFICATION) {
15246                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15247                                + ivi.getStatusString());
15248                    }
15249                    return;
15250                }
15251            }
15252
15253            // If any filters need to be verified, then all need to be.
15254            boolean needToVerify = false;
15255            for (PackageParser.Activity a : pkg.activities) {
15256                for (ActivityIntentInfo filter : a.intents) {
15257                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15258                        if (DEBUG_DOMAIN_VERIFICATION) {
15259                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15260                        }
15261                        needToVerify = true;
15262                        break;
15263                    }
15264                }
15265            }
15266
15267            if (needToVerify) {
15268                final int verificationId = mIntentFilterVerificationToken++;
15269                for (PackageParser.Activity a : pkg.activities) {
15270                    for (ActivityIntentInfo filter : a.intents) {
15271                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15272                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15273                                    "Verification needed for IntentFilter:" + filter.toString());
15274                            mIntentFilterVerifier.addOneIntentFilterVerification(
15275                                    verifierUid, userId, verificationId, filter, packageName);
15276                            count++;
15277                        }
15278                    }
15279                }
15280            }
15281        }
15282
15283        if (count > 0) {
15284            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15285                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15286                    +  " for userId:" + userId);
15287            mIntentFilterVerifier.startVerifications(userId);
15288        } else {
15289            if (DEBUG_DOMAIN_VERIFICATION) {
15290                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15291            }
15292        }
15293    }
15294
15295    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15296        final ComponentName cn  = filter.activity.getComponentName();
15297        final String packageName = cn.getPackageName();
15298
15299        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15300                packageName);
15301        if (ivi == null) {
15302            return true;
15303        }
15304        int status = ivi.getStatus();
15305        switch (status) {
15306            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15307            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15308                return true;
15309
15310            default:
15311                // Nothing to do
15312                return false;
15313        }
15314    }
15315
15316    private static boolean isMultiArch(ApplicationInfo info) {
15317        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15318    }
15319
15320    private static boolean isExternal(PackageParser.Package pkg) {
15321        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15322    }
15323
15324    private static boolean isExternal(PackageSetting ps) {
15325        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15326    }
15327
15328    private static boolean isEphemeral(PackageParser.Package pkg) {
15329        return pkg.applicationInfo.isEphemeralApp();
15330    }
15331
15332    private static boolean isEphemeral(PackageSetting ps) {
15333        return ps.pkg != null && isEphemeral(ps.pkg);
15334    }
15335
15336    private static boolean isSystemApp(PackageParser.Package pkg) {
15337        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15338    }
15339
15340    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15341        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15342    }
15343
15344    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15345        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15346    }
15347
15348    private static boolean isSystemApp(PackageSetting ps) {
15349        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15350    }
15351
15352    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15353        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15354    }
15355
15356    private int packageFlagsToInstallFlags(PackageSetting ps) {
15357        int installFlags = 0;
15358        if (isEphemeral(ps)) {
15359            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15360        }
15361        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15362            // This existing package was an external ASEC install when we have
15363            // the external flag without a UUID
15364            installFlags |= PackageManager.INSTALL_EXTERNAL;
15365        }
15366        if (ps.isForwardLocked()) {
15367            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15368        }
15369        return installFlags;
15370    }
15371
15372    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15373        if (isExternal(pkg)) {
15374            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15375                return StorageManager.UUID_PRIMARY_PHYSICAL;
15376            } else {
15377                return pkg.volumeUuid;
15378            }
15379        } else {
15380            return StorageManager.UUID_PRIVATE_INTERNAL;
15381        }
15382    }
15383
15384    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15385        if (isExternal(pkg)) {
15386            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15387                return mSettings.getExternalVersion();
15388            } else {
15389                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15390            }
15391        } else {
15392            return mSettings.getInternalVersion();
15393        }
15394    }
15395
15396    private void deleteTempPackageFiles() {
15397        final FilenameFilter filter = new FilenameFilter() {
15398            public boolean accept(File dir, String name) {
15399                return name.startsWith("vmdl") && name.endsWith(".tmp");
15400            }
15401        };
15402        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15403            file.delete();
15404        }
15405    }
15406
15407    @Override
15408    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15409            int flags) {
15410        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15411                flags);
15412    }
15413
15414    @Override
15415    public void deletePackage(final String packageName,
15416            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15417        mContext.enforceCallingOrSelfPermission(
15418                android.Manifest.permission.DELETE_PACKAGES, null);
15419        Preconditions.checkNotNull(packageName);
15420        Preconditions.checkNotNull(observer);
15421        final int uid = Binder.getCallingUid();
15422        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15423        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15424        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15425            mContext.enforceCallingOrSelfPermission(
15426                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15427                    "deletePackage for user " + userId);
15428        }
15429
15430        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15431            try {
15432                observer.onPackageDeleted(packageName,
15433                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15434            } catch (RemoteException re) {
15435            }
15436            return;
15437        }
15438
15439        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15440            try {
15441                observer.onPackageDeleted(packageName,
15442                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15443            } catch (RemoteException re) {
15444            }
15445            return;
15446        }
15447
15448        if (DEBUG_REMOVE) {
15449            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15450                    + " deleteAllUsers: " + deleteAllUsers );
15451        }
15452        // Queue up an async operation since the package deletion may take a little while.
15453        mHandler.post(new Runnable() {
15454            public void run() {
15455                mHandler.removeCallbacks(this);
15456                int returnCode;
15457                if (!deleteAllUsers) {
15458                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15459                } else {
15460                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15461                    // If nobody is blocking uninstall, proceed with delete for all users
15462                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15463                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15464                    } else {
15465                        // Otherwise uninstall individually for users with blockUninstalls=false
15466                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15467                        for (int userId : users) {
15468                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15469                                returnCode = deletePackageX(packageName, userId, userFlags);
15470                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15471                                    Slog.w(TAG, "Package delete failed for user " + userId
15472                                            + ", returnCode " + returnCode);
15473                                }
15474                            }
15475                        }
15476                        // The app has only been marked uninstalled for certain users.
15477                        // We still need to report that delete was blocked
15478                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15479                    }
15480                }
15481                try {
15482                    observer.onPackageDeleted(packageName, returnCode, null);
15483                } catch (RemoteException e) {
15484                    Log.i(TAG, "Observer no longer exists.");
15485                } //end catch
15486            } //end run
15487        });
15488    }
15489
15490    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15491        int[] result = EMPTY_INT_ARRAY;
15492        for (int userId : userIds) {
15493            if (getBlockUninstallForUser(packageName, userId)) {
15494                result = ArrayUtils.appendInt(result, userId);
15495            }
15496        }
15497        return result;
15498    }
15499
15500    @Override
15501    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15502        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15503    }
15504
15505    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15506        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15507                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15508        try {
15509            if (dpm != null) {
15510                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15511                        /* callingUserOnly =*/ false);
15512                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15513                        : deviceOwnerComponentName.getPackageName();
15514                // Does the package contains the device owner?
15515                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15516                // this check is probably not needed, since DO should be registered as a device
15517                // admin on some user too. (Original bug for this: b/17657954)
15518                if (packageName.equals(deviceOwnerPackageName)) {
15519                    return true;
15520                }
15521                // Does it contain a device admin for any user?
15522                int[] users;
15523                if (userId == UserHandle.USER_ALL) {
15524                    users = sUserManager.getUserIds();
15525                } else {
15526                    users = new int[]{userId};
15527                }
15528                for (int i = 0; i < users.length; ++i) {
15529                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15530                        return true;
15531                    }
15532                }
15533            }
15534        } catch (RemoteException e) {
15535        }
15536        return false;
15537    }
15538
15539    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15540        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15541    }
15542
15543    /**
15544     *  This method is an internal method that could be get invoked either
15545     *  to delete an installed package or to clean up a failed installation.
15546     *  After deleting an installed package, a broadcast is sent to notify any
15547     *  listeners that the package has been removed. For cleaning up a failed
15548     *  installation, the broadcast is not necessary since the package's
15549     *  installation wouldn't have sent the initial broadcast either
15550     *  The key steps in deleting a package are
15551     *  deleting the package information in internal structures like mPackages,
15552     *  deleting the packages base directories through installd
15553     *  updating mSettings to reflect current status
15554     *  persisting settings for later use
15555     *  sending a broadcast if necessary
15556     */
15557    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15558        final PackageRemovedInfo info = new PackageRemovedInfo();
15559        final boolean res;
15560
15561        final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15562                ? UserHandle.ALL : new UserHandle(userId);
15563
15564        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
15565            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15566            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15567        }
15568
15569        PackageSetting uninstalledPs = null;
15570
15571        // for the uninstall-updates case and restricted profiles, remember the per-
15572        // user handle installed state
15573        int[] allUsers;
15574        synchronized (mPackages) {
15575            uninstalledPs = mSettings.mPackages.get(packageName);
15576            if (uninstalledPs == null) {
15577                Slog.w(TAG, "Not removing non-existent package " + packageName);
15578                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15579            }
15580            allUsers = sUserManager.getUserIds();
15581            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15582        }
15583
15584        synchronized (mInstallLock) {
15585            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15586            try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags,
15587                    "deletePackageX")) {
15588                res = deletePackageLIF(packageName, removeForUser, true, allUsers,
15589                        deleteFlags | REMOVE_CHATTY, info, true, null);
15590            }
15591            synchronized (mPackages) {
15592                if (res) {
15593                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15594                }
15595            }
15596        }
15597
15598        if (res) {
15599            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15600            info.sendPackageRemovedBroadcasts(killApp);
15601            info.sendSystemPackageUpdatedBroadcasts();
15602            info.sendSystemPackageAppearedBroadcasts();
15603        }
15604        // Force a gc here.
15605        Runtime.getRuntime().gc();
15606        // Delete the resources here after sending the broadcast to let
15607        // other processes clean up before deleting resources.
15608        if (info.args != null) {
15609            synchronized (mInstallLock) {
15610                info.args.doPostDeleteLI(true);
15611            }
15612        }
15613
15614        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15615    }
15616
15617    class PackageRemovedInfo {
15618        String removedPackage;
15619        int uid = -1;
15620        int removedAppId = -1;
15621        int[] origUsers;
15622        int[] removedUsers = null;
15623        boolean isRemovedPackageSystemUpdate = false;
15624        boolean isUpdate;
15625        boolean dataRemoved;
15626        boolean removedForAllUsers;
15627        // Clean up resources deleted packages.
15628        InstallArgs args = null;
15629        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15630        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15631
15632        void sendPackageRemovedBroadcasts(boolean killApp) {
15633            sendPackageRemovedBroadcastInternal(killApp);
15634            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15635            for (int i = 0; i < childCount; i++) {
15636                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15637                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15638            }
15639        }
15640
15641        void sendSystemPackageUpdatedBroadcasts() {
15642            if (isRemovedPackageSystemUpdate) {
15643                sendSystemPackageUpdatedBroadcastsInternal();
15644                final int childCount = (removedChildPackages != null)
15645                        ? removedChildPackages.size() : 0;
15646                for (int i = 0; i < childCount; i++) {
15647                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15648                    if (childInfo.isRemovedPackageSystemUpdate) {
15649                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15650                    }
15651                }
15652            }
15653        }
15654
15655        void sendSystemPackageAppearedBroadcasts() {
15656            final int packageCount = (appearedChildPackages != null)
15657                    ? appearedChildPackages.size() : 0;
15658            for (int i = 0; i < packageCount; i++) {
15659                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15660                for (int userId : installedInfo.newUsers) {
15661                    sendPackageAddedForUser(installedInfo.name, true,
15662                            UserHandle.getAppId(installedInfo.uid), userId);
15663                }
15664            }
15665        }
15666
15667        private void sendSystemPackageUpdatedBroadcastsInternal() {
15668            Bundle extras = new Bundle(2);
15669            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15670            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15671            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15672                    extras, 0, null, null, null);
15673            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15674                    extras, 0, null, null, null);
15675            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15676                    null, 0, removedPackage, null, null);
15677        }
15678
15679        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15680            Bundle extras = new Bundle(2);
15681            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15682            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15683            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15684            if (isUpdate || isRemovedPackageSystemUpdate) {
15685                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15686            }
15687            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15688            if (removedPackage != null) {
15689                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15690                        extras, 0, null, null, removedUsers);
15691                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15692                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15693                            removedPackage, extras, 0, null, null, removedUsers);
15694                }
15695            }
15696            if (removedAppId >= 0) {
15697                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15698                        removedUsers);
15699            }
15700        }
15701    }
15702
15703    /*
15704     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15705     * flag is not set, the data directory is removed as well.
15706     * make sure this flag is set for partially installed apps. If not its meaningless to
15707     * delete a partially installed application.
15708     */
15709    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15710            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15711        String packageName = ps.name;
15712        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15713        // Retrieve object to delete permissions for shared user later on
15714        final PackageParser.Package deletedPkg;
15715        final PackageSetting deletedPs;
15716        // reader
15717        synchronized (mPackages) {
15718            deletedPkg = mPackages.get(packageName);
15719            deletedPs = mSettings.mPackages.get(packageName);
15720            if (outInfo != null) {
15721                outInfo.removedPackage = packageName;
15722                outInfo.removedUsers = deletedPs != null
15723                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15724                        : null;
15725            }
15726        }
15727
15728        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15729
15730        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15731            final PackageParser.Package resolvedPkg;
15732            if (deletedPkg != null) {
15733                resolvedPkg = deletedPkg;
15734            } else {
15735                // We don't have a parsed package when it lives on an ejected
15736                // adopted storage device, so fake something together
15737                resolvedPkg = new PackageParser.Package(ps.name);
15738                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15739            }
15740            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15741                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15742            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15743            if (outInfo != null) {
15744                outInfo.dataRemoved = true;
15745            }
15746            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15747        }
15748
15749        // writer
15750        synchronized (mPackages) {
15751            if (deletedPs != null) {
15752                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15753                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15754                    clearDefaultBrowserIfNeeded(packageName);
15755                    if (outInfo != null) {
15756                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15757                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15758                    }
15759                    updatePermissionsLPw(deletedPs.name, null, 0);
15760                    if (deletedPs.sharedUser != null) {
15761                        // Remove permissions associated with package. Since runtime
15762                        // permissions are per user we have to kill the removed package
15763                        // or packages running under the shared user of the removed
15764                        // package if revoking the permissions requested only by the removed
15765                        // package is successful and this causes a change in gids.
15766                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15767                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15768                                    userId);
15769                            if (userIdToKill == UserHandle.USER_ALL
15770                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15771                                // If gids changed for this user, kill all affected packages.
15772                                mHandler.post(new Runnable() {
15773                                    @Override
15774                                    public void run() {
15775                                        // This has to happen with no lock held.
15776                                        killApplication(deletedPs.name, deletedPs.appId,
15777                                                KILL_APP_REASON_GIDS_CHANGED);
15778                                    }
15779                                });
15780                                break;
15781                            }
15782                        }
15783                    }
15784                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15785                }
15786                // make sure to preserve per-user disabled state if this removal was just
15787                // a downgrade of a system app to the factory package
15788                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15789                    if (DEBUG_REMOVE) {
15790                        Slog.d(TAG, "Propagating install state across downgrade");
15791                    }
15792                    for (int userId : allUserHandles) {
15793                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15794                        if (DEBUG_REMOVE) {
15795                            Slog.d(TAG, "    user " + userId + " => " + installed);
15796                        }
15797                        ps.setInstalled(installed, userId);
15798                    }
15799                }
15800            }
15801            // can downgrade to reader
15802            if (writeSettings) {
15803                // Save settings now
15804                mSettings.writeLPr();
15805            }
15806        }
15807        if (outInfo != null) {
15808            // A user ID was deleted here. Go through all users and remove it
15809            // from KeyStore.
15810            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15811        }
15812    }
15813
15814    static boolean locationIsPrivileged(File path) {
15815        try {
15816            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15817                    .getCanonicalPath();
15818            return path.getCanonicalPath().startsWith(privilegedAppDir);
15819        } catch (IOException e) {
15820            Slog.e(TAG, "Unable to access code path " + path);
15821        }
15822        return false;
15823    }
15824
15825    /*
15826     * Tries to delete system package.
15827     */
15828    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15829            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15830            boolean writeSettings) {
15831        if (deletedPs.parentPackageName != null) {
15832            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15833            return false;
15834        }
15835
15836        final boolean applyUserRestrictions
15837                = (allUserHandles != null) && (outInfo.origUsers != null);
15838        final PackageSetting disabledPs;
15839        // Confirm if the system package has been updated
15840        // An updated system app can be deleted. This will also have to restore
15841        // the system pkg from system partition
15842        // reader
15843        synchronized (mPackages) {
15844            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15845        }
15846
15847        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15848                + " disabledPs=" + disabledPs);
15849
15850        if (disabledPs == null) {
15851            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15852            return false;
15853        } else if (DEBUG_REMOVE) {
15854            Slog.d(TAG, "Deleting system pkg from data partition");
15855        }
15856
15857        if (DEBUG_REMOVE) {
15858            if (applyUserRestrictions) {
15859                Slog.d(TAG, "Remembering install states:");
15860                for (int userId : allUserHandles) {
15861                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15862                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15863                }
15864            }
15865        }
15866
15867        // Delete the updated package
15868        outInfo.isRemovedPackageSystemUpdate = true;
15869        if (outInfo.removedChildPackages != null) {
15870            final int childCount = (deletedPs.childPackageNames != null)
15871                    ? deletedPs.childPackageNames.size() : 0;
15872            for (int i = 0; i < childCount; i++) {
15873                String childPackageName = deletedPs.childPackageNames.get(i);
15874                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15875                        .contains(childPackageName)) {
15876                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15877                            childPackageName);
15878                    if (childInfo != null) {
15879                        childInfo.isRemovedPackageSystemUpdate = true;
15880                    }
15881                }
15882            }
15883        }
15884
15885        if (disabledPs.versionCode < deletedPs.versionCode) {
15886            // Delete data for downgrades
15887            flags &= ~PackageManager.DELETE_KEEP_DATA;
15888        } else {
15889            // Preserve data by setting flag
15890            flags |= PackageManager.DELETE_KEEP_DATA;
15891        }
15892
15893        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15894                outInfo, writeSettings, disabledPs.pkg);
15895        if (!ret) {
15896            return false;
15897        }
15898
15899        // writer
15900        synchronized (mPackages) {
15901            // Reinstate the old system package
15902            enableSystemPackageLPw(disabledPs.pkg);
15903            // Remove any native libraries from the upgraded package.
15904            removeNativeBinariesLI(deletedPs);
15905        }
15906
15907        // Install the system package
15908        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15909        int parseFlags = mDefParseFlags
15910                | PackageParser.PARSE_MUST_BE_APK
15911                | PackageParser.PARSE_IS_SYSTEM
15912                | PackageParser.PARSE_IS_SYSTEM_DIR;
15913        if (locationIsPrivileged(disabledPs.codePath)) {
15914            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15915        }
15916
15917        final PackageParser.Package newPkg;
15918        try {
15919            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15920        } catch (PackageManagerException e) {
15921            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15922                    + e.getMessage());
15923            return false;
15924        }
15925
15926        prepareAppDataAfterInstallLIF(newPkg);
15927
15928        // writer
15929        synchronized (mPackages) {
15930            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15931
15932            // Propagate the permissions state as we do not want to drop on the floor
15933            // runtime permissions. The update permissions method below will take
15934            // care of removing obsolete permissions and grant install permissions.
15935            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15936            updatePermissionsLPw(newPkg.packageName, newPkg,
15937                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15938
15939            if (applyUserRestrictions) {
15940                if (DEBUG_REMOVE) {
15941                    Slog.d(TAG, "Propagating install state across reinstall");
15942                }
15943                for (int userId : allUserHandles) {
15944                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15945                    if (DEBUG_REMOVE) {
15946                        Slog.d(TAG, "    user " + userId + " => " + installed);
15947                    }
15948                    ps.setInstalled(installed, userId);
15949
15950                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15951                }
15952                // Regardless of writeSettings we need to ensure that this restriction
15953                // state propagation is persisted
15954                mSettings.writeAllUsersPackageRestrictionsLPr();
15955            }
15956            // can downgrade to reader here
15957            if (writeSettings) {
15958                mSettings.writeLPr();
15959            }
15960        }
15961        return true;
15962    }
15963
15964    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15965            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15966            PackageRemovedInfo outInfo, boolean writeSettings,
15967            PackageParser.Package replacingPackage) {
15968        synchronized (mPackages) {
15969            if (outInfo != null) {
15970                outInfo.uid = ps.appId;
15971            }
15972
15973            if (outInfo != null && outInfo.removedChildPackages != null) {
15974                final int childCount = (ps.childPackageNames != null)
15975                        ? ps.childPackageNames.size() : 0;
15976                for (int i = 0; i < childCount; i++) {
15977                    String childPackageName = ps.childPackageNames.get(i);
15978                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15979                    if (childPs == null) {
15980                        return false;
15981                    }
15982                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15983                            childPackageName);
15984                    if (childInfo != null) {
15985                        childInfo.uid = childPs.appId;
15986                    }
15987                }
15988            }
15989        }
15990
15991        // Delete package data from internal structures and also remove data if flag is set
15992        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15993
15994        // Delete the child packages data
15995        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15996        for (int i = 0; i < childCount; i++) {
15997            PackageSetting childPs;
15998            synchronized (mPackages) {
15999                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16000            }
16001            if (childPs != null) {
16002                PackageRemovedInfo childOutInfo = (outInfo != null
16003                        && outInfo.removedChildPackages != null)
16004                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16005                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16006                        && (replacingPackage != null
16007                        && !replacingPackage.hasChildPackage(childPs.name))
16008                        ? flags & ~DELETE_KEEP_DATA : flags;
16009                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16010                        deleteFlags, writeSettings);
16011            }
16012        }
16013
16014        // Delete application code and resources only for parent packages
16015        if (ps.parentPackageName == null) {
16016            if (deleteCodeAndResources && (outInfo != null)) {
16017                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16018                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16019                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16020            }
16021        }
16022
16023        return true;
16024    }
16025
16026    @Override
16027    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16028            int userId) {
16029        mContext.enforceCallingOrSelfPermission(
16030                android.Manifest.permission.DELETE_PACKAGES, null);
16031        synchronized (mPackages) {
16032            PackageSetting ps = mSettings.mPackages.get(packageName);
16033            if (ps == null) {
16034                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16035                return false;
16036            }
16037            if (!ps.getInstalled(userId)) {
16038                // Can't block uninstall for an app that is not installed or enabled.
16039                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16040                return false;
16041            }
16042            ps.setBlockUninstall(blockUninstall, userId);
16043            mSettings.writePackageRestrictionsLPr(userId);
16044        }
16045        return true;
16046    }
16047
16048    @Override
16049    public boolean getBlockUninstallForUser(String packageName, int userId) {
16050        synchronized (mPackages) {
16051            PackageSetting ps = mSettings.mPackages.get(packageName);
16052            if (ps == null) {
16053                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16054                return false;
16055            }
16056            return ps.getBlockUninstall(userId);
16057        }
16058    }
16059
16060    @Override
16061    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16062        int callingUid = Binder.getCallingUid();
16063        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16064            throw new SecurityException(
16065                    "setRequiredForSystemUser can only be run by the system or root");
16066        }
16067        synchronized (mPackages) {
16068            PackageSetting ps = mSettings.mPackages.get(packageName);
16069            if (ps == null) {
16070                Log.w(TAG, "Package doesn't exist: " + packageName);
16071                return false;
16072            }
16073            if (systemUserApp) {
16074                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16075            } else {
16076                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16077            }
16078            mSettings.writeLPr();
16079        }
16080        return true;
16081    }
16082
16083    /*
16084     * This method handles package deletion in general
16085     */
16086    private boolean deletePackageLIF(String packageName, UserHandle user,
16087            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16088            PackageRemovedInfo outInfo, boolean writeSettings,
16089            PackageParser.Package replacingPackage) {
16090        if (packageName == null) {
16091            Slog.w(TAG, "Attempt to delete null packageName.");
16092            return false;
16093        }
16094
16095        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16096
16097        PackageSetting ps;
16098
16099        synchronized (mPackages) {
16100            ps = mSettings.mPackages.get(packageName);
16101            if (ps == null) {
16102                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16103                return false;
16104            }
16105
16106            if (ps.parentPackageName != null && (!isSystemApp(ps)
16107                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16108                if (DEBUG_REMOVE) {
16109                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16110                            + ((user == null) ? UserHandle.USER_ALL : user));
16111                }
16112                final int removedUserId = (user != null) ? user.getIdentifier()
16113                        : UserHandle.USER_ALL;
16114                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16115                    return false;
16116                }
16117                markPackageUninstalledForUserLPw(ps, user);
16118                scheduleWritePackageRestrictionsLocked(user);
16119                return true;
16120            }
16121        }
16122
16123        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16124                && user.getIdentifier() != UserHandle.USER_ALL)) {
16125            // The caller is asking that the package only be deleted for a single
16126            // user.  To do this, we just mark its uninstalled state and delete
16127            // its data. If this is a system app, we only allow this to happen if
16128            // they have set the special DELETE_SYSTEM_APP which requests different
16129            // semantics than normal for uninstalling system apps.
16130            markPackageUninstalledForUserLPw(ps, user);
16131
16132            if (!isSystemApp(ps)) {
16133                // Do not uninstall the APK if an app should be cached
16134                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16135                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16136                    // Other user still have this package installed, so all
16137                    // we need to do is clear this user's data and save that
16138                    // it is uninstalled.
16139                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16140                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16141                        return false;
16142                    }
16143                    scheduleWritePackageRestrictionsLocked(user);
16144                    return true;
16145                } else {
16146                    // We need to set it back to 'installed' so the uninstall
16147                    // broadcasts will be sent correctly.
16148                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16149                    ps.setInstalled(true, user.getIdentifier());
16150                }
16151            } else {
16152                // This is a system app, so we assume that the
16153                // other users still have this package installed, so all
16154                // we need to do is clear this user's data and save that
16155                // it is uninstalled.
16156                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16157                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16158                    return false;
16159                }
16160                scheduleWritePackageRestrictionsLocked(user);
16161                return true;
16162            }
16163        }
16164
16165        // If we are deleting a composite package for all users, keep track
16166        // of result for each child.
16167        if (ps.childPackageNames != null && outInfo != null) {
16168            synchronized (mPackages) {
16169                final int childCount = ps.childPackageNames.size();
16170                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16171                for (int i = 0; i < childCount; i++) {
16172                    String childPackageName = ps.childPackageNames.get(i);
16173                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16174                    childInfo.removedPackage = childPackageName;
16175                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16176                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16177                    if (childPs != null) {
16178                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16179                    }
16180                }
16181            }
16182        }
16183
16184        boolean ret = false;
16185        if (isSystemApp(ps)) {
16186            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16187            // When an updated system application is deleted we delete the existing resources
16188            // as well and fall back to existing code in system partition
16189            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16190        } else {
16191            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16192            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16193                    outInfo, writeSettings, replacingPackage);
16194        }
16195
16196        // Take a note whether we deleted the package for all users
16197        if (outInfo != null) {
16198            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16199            if (outInfo.removedChildPackages != null) {
16200                synchronized (mPackages) {
16201                    final int childCount = outInfo.removedChildPackages.size();
16202                    for (int i = 0; i < childCount; i++) {
16203                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16204                        if (childInfo != null) {
16205                            childInfo.removedForAllUsers = mPackages.get(
16206                                    childInfo.removedPackage) == null;
16207                        }
16208                    }
16209                }
16210            }
16211            // If we uninstalled an update to a system app there may be some
16212            // child packages that appeared as they are declared in the system
16213            // app but were not declared in the update.
16214            if (isSystemApp(ps)) {
16215                synchronized (mPackages) {
16216                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16217                    final int childCount = (updatedPs.childPackageNames != null)
16218                            ? updatedPs.childPackageNames.size() : 0;
16219                    for (int i = 0; i < childCount; i++) {
16220                        String childPackageName = updatedPs.childPackageNames.get(i);
16221                        if (outInfo.removedChildPackages == null
16222                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16223                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16224                            if (childPs == null) {
16225                                continue;
16226                            }
16227                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16228                            installRes.name = childPackageName;
16229                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16230                            installRes.pkg = mPackages.get(childPackageName);
16231                            installRes.uid = childPs.pkg.applicationInfo.uid;
16232                            if (outInfo.appearedChildPackages == null) {
16233                                outInfo.appearedChildPackages = new ArrayMap<>();
16234                            }
16235                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16236                        }
16237                    }
16238                }
16239            }
16240        }
16241
16242        return ret;
16243    }
16244
16245    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16246        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16247                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16248        for (int nextUserId : userIds) {
16249            if (DEBUG_REMOVE) {
16250                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16251            }
16252            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16253                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16254                    false /*hidden*/, false /*suspended*/, null, null, null,
16255                    false /*blockUninstall*/,
16256                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16257        }
16258    }
16259
16260    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16261            PackageRemovedInfo outInfo) {
16262        final PackageParser.Package pkg;
16263        synchronized (mPackages) {
16264            pkg = mPackages.get(ps.name);
16265        }
16266
16267        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16268                : new int[] {userId};
16269        for (int nextUserId : userIds) {
16270            if (DEBUG_REMOVE) {
16271                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16272                        + nextUserId);
16273            }
16274
16275            destroyAppDataLIF(pkg, userId,
16276                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16277            destroyAppProfilesLIF(pkg, userId);
16278            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16279            schedulePackageCleaning(ps.name, nextUserId, false);
16280            synchronized (mPackages) {
16281                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16282                    scheduleWritePackageRestrictionsLocked(nextUserId);
16283                }
16284                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16285            }
16286        }
16287
16288        if (outInfo != null) {
16289            outInfo.removedPackage = ps.name;
16290            outInfo.removedAppId = ps.appId;
16291            outInfo.removedUsers = userIds;
16292        }
16293
16294        return true;
16295    }
16296
16297    private final class ClearStorageConnection implements ServiceConnection {
16298        IMediaContainerService mContainerService;
16299
16300        @Override
16301        public void onServiceConnected(ComponentName name, IBinder service) {
16302            synchronized (this) {
16303                mContainerService = IMediaContainerService.Stub.asInterface(service);
16304                notifyAll();
16305            }
16306        }
16307
16308        @Override
16309        public void onServiceDisconnected(ComponentName name) {
16310        }
16311    }
16312
16313    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16314        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16315
16316        final boolean mounted;
16317        if (Environment.isExternalStorageEmulated()) {
16318            mounted = true;
16319        } else {
16320            final String status = Environment.getExternalStorageState();
16321
16322            mounted = status.equals(Environment.MEDIA_MOUNTED)
16323                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16324        }
16325
16326        if (!mounted) {
16327            return;
16328        }
16329
16330        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16331        int[] users;
16332        if (userId == UserHandle.USER_ALL) {
16333            users = sUserManager.getUserIds();
16334        } else {
16335            users = new int[] { userId };
16336        }
16337        final ClearStorageConnection conn = new ClearStorageConnection();
16338        if (mContext.bindServiceAsUser(
16339                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16340            try {
16341                for (int curUser : users) {
16342                    long timeout = SystemClock.uptimeMillis() + 5000;
16343                    synchronized (conn) {
16344                        long now = SystemClock.uptimeMillis();
16345                        while (conn.mContainerService == null && now < timeout) {
16346                            try {
16347                                conn.wait(timeout - now);
16348                            } catch (InterruptedException e) {
16349                            }
16350                        }
16351                    }
16352                    if (conn.mContainerService == null) {
16353                        return;
16354                    }
16355
16356                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16357                    clearDirectory(conn.mContainerService,
16358                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16359                    if (allData) {
16360                        clearDirectory(conn.mContainerService,
16361                                userEnv.buildExternalStorageAppDataDirs(packageName));
16362                        clearDirectory(conn.mContainerService,
16363                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16364                    }
16365                }
16366            } finally {
16367                mContext.unbindService(conn);
16368            }
16369        }
16370    }
16371
16372    @Override
16373    public void clearApplicationProfileData(String packageName) {
16374        enforceSystemOrRoot("Only the system can clear all profile data");
16375
16376        final PackageParser.Package pkg;
16377        synchronized (mPackages) {
16378            pkg = mPackages.get(packageName);
16379        }
16380
16381        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16382            synchronized (mInstallLock) {
16383                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16384                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16385                        true /* removeBaseMarker */);
16386            }
16387        }
16388    }
16389
16390    @Override
16391    public void clearApplicationUserData(final String packageName,
16392            final IPackageDataObserver observer, final int userId) {
16393        mContext.enforceCallingOrSelfPermission(
16394                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16395
16396        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16397                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16398
16399        final DevicePolicyManagerInternal dpmi = LocalServices
16400                .getService(DevicePolicyManagerInternal.class);
16401        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
16402            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
16403        }
16404        // Queue up an async operation since the package deletion may take a little while.
16405        mHandler.post(new Runnable() {
16406            public void run() {
16407                mHandler.removeCallbacks(this);
16408                final boolean succeeded;
16409                try (PackageFreezer freezer = freezePackage(packageName,
16410                        "clearApplicationUserData")) {
16411                    synchronized (mInstallLock) {
16412                        succeeded = clearApplicationUserDataLIF(packageName, userId);
16413                    }
16414                    clearExternalStorageDataSync(packageName, userId, true);
16415                }
16416                if (succeeded) {
16417                    // invoke DeviceStorageMonitor's update method to clear any notifications
16418                    DeviceStorageMonitorInternal dsm = LocalServices
16419                            .getService(DeviceStorageMonitorInternal.class);
16420                    if (dsm != null) {
16421                        dsm.checkMemory();
16422                    }
16423                }
16424                if(observer != null) {
16425                    try {
16426                        observer.onRemoveCompleted(packageName, succeeded);
16427                    } catch (RemoteException e) {
16428                        Log.i(TAG, "Observer no longer exists.");
16429                    }
16430                } //end if observer
16431            } //end run
16432        });
16433    }
16434
16435    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
16436        if (packageName == null) {
16437            Slog.w(TAG, "Attempt to delete null packageName.");
16438            return false;
16439        }
16440
16441        // Try finding details about the requested package
16442        PackageParser.Package pkg;
16443        synchronized (mPackages) {
16444            pkg = mPackages.get(packageName);
16445            if (pkg == null) {
16446                final PackageSetting ps = mSettings.mPackages.get(packageName);
16447                if (ps != null) {
16448                    pkg = ps.pkg;
16449                }
16450            }
16451
16452            if (pkg == null) {
16453                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16454                return false;
16455            }
16456
16457            PackageSetting ps = (PackageSetting) pkg.mExtras;
16458            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16459        }
16460
16461        clearAppDataLIF(pkg, userId,
16462                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16463
16464        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16465        removeKeystoreDataIfNeeded(userId, appId);
16466
16467        UserManagerInternal umInternal = getUserManagerInternal();
16468        final int flags;
16469        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
16470            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
16471        } else if (umInternal.isUserRunning(userId)) {
16472            flags = StorageManager.FLAG_STORAGE_DE;
16473        } else {
16474            flags = 0;
16475        }
16476        prepareAppDataContentsLIF(pkg, userId, flags);
16477
16478        return true;
16479    }
16480
16481    /**
16482     * Reverts user permission state changes (permissions and flags) in
16483     * all packages for a given user.
16484     *
16485     * @param userId The device user for which to do a reset.
16486     */
16487    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
16488        final int packageCount = mPackages.size();
16489        for (int i = 0; i < packageCount; i++) {
16490            PackageParser.Package pkg = mPackages.valueAt(i);
16491            PackageSetting ps = (PackageSetting) pkg.mExtras;
16492            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
16493        }
16494    }
16495
16496    private void resetNetworkPolicies(int userId) {
16497        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
16498    }
16499
16500    /**
16501     * Reverts user permission state changes (permissions and flags).
16502     *
16503     * @param ps The package for which to reset.
16504     * @param userId The device user for which to do a reset.
16505     */
16506    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
16507            final PackageSetting ps, final int userId) {
16508        if (ps.pkg == null) {
16509            return;
16510        }
16511
16512        // These are flags that can change base on user actions.
16513        final int userSettableMask = FLAG_PERMISSION_USER_SET
16514                | FLAG_PERMISSION_USER_FIXED
16515                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
16516                | FLAG_PERMISSION_REVIEW_REQUIRED;
16517
16518        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
16519                | FLAG_PERMISSION_POLICY_FIXED;
16520
16521        boolean writeInstallPermissions = false;
16522        boolean writeRuntimePermissions = false;
16523
16524        final int permissionCount = ps.pkg.requestedPermissions.size();
16525        for (int i = 0; i < permissionCount; i++) {
16526            String permission = ps.pkg.requestedPermissions.get(i);
16527
16528            BasePermission bp = mSettings.mPermissions.get(permission);
16529            if (bp == null) {
16530                continue;
16531            }
16532
16533            // If shared user we just reset the state to which only this app contributed.
16534            if (ps.sharedUser != null) {
16535                boolean used = false;
16536                final int packageCount = ps.sharedUser.packages.size();
16537                for (int j = 0; j < packageCount; j++) {
16538                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
16539                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
16540                            && pkg.pkg.requestedPermissions.contains(permission)) {
16541                        used = true;
16542                        break;
16543                    }
16544                }
16545                if (used) {
16546                    continue;
16547                }
16548            }
16549
16550            PermissionsState permissionsState = ps.getPermissionsState();
16551
16552            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
16553
16554            // Always clear the user settable flags.
16555            final boolean hasInstallState = permissionsState.getInstallPermissionState(
16556                    bp.name) != null;
16557            // If permission review is enabled and this is a legacy app, mark the
16558            // permission as requiring a review as this is the initial state.
16559            int flags = 0;
16560            if (Build.PERMISSIONS_REVIEW_REQUIRED
16561                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
16562                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
16563            }
16564            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
16565                if (hasInstallState) {
16566                    writeInstallPermissions = true;
16567                } else {
16568                    writeRuntimePermissions = true;
16569                }
16570            }
16571
16572            // Below is only runtime permission handling.
16573            if (!bp.isRuntime()) {
16574                continue;
16575            }
16576
16577            // Never clobber system or policy.
16578            if ((oldFlags & policyOrSystemFlags) != 0) {
16579                continue;
16580            }
16581
16582            // If this permission was granted by default, make sure it is.
16583            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
16584                if (permissionsState.grantRuntimePermission(bp, userId)
16585                        != PERMISSION_OPERATION_FAILURE) {
16586                    writeRuntimePermissions = true;
16587                }
16588            // If permission review is enabled the permissions for a legacy apps
16589            // are represented as constantly granted runtime ones, so don't revoke.
16590            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
16591                // Otherwise, reset the permission.
16592                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
16593                switch (revokeResult) {
16594                    case PERMISSION_OPERATION_SUCCESS:
16595                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
16596                        writeRuntimePermissions = true;
16597                        final int appId = ps.appId;
16598                        mHandler.post(new Runnable() {
16599                            @Override
16600                            public void run() {
16601                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
16602                            }
16603                        });
16604                    } break;
16605                }
16606            }
16607        }
16608
16609        // Synchronously write as we are taking permissions away.
16610        if (writeRuntimePermissions) {
16611            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
16612        }
16613
16614        // Synchronously write as we are taking permissions away.
16615        if (writeInstallPermissions) {
16616            mSettings.writeLPr();
16617        }
16618    }
16619
16620    /**
16621     * Remove entries from the keystore daemon. Will only remove it if the
16622     * {@code appId} is valid.
16623     */
16624    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
16625        if (appId < 0) {
16626            return;
16627        }
16628
16629        final KeyStore keyStore = KeyStore.getInstance();
16630        if (keyStore != null) {
16631            if (userId == UserHandle.USER_ALL) {
16632                for (final int individual : sUserManager.getUserIds()) {
16633                    keyStore.clearUid(UserHandle.getUid(individual, appId));
16634                }
16635            } else {
16636                keyStore.clearUid(UserHandle.getUid(userId, appId));
16637            }
16638        } else {
16639            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
16640        }
16641    }
16642
16643    @Override
16644    public void deleteApplicationCacheFiles(final String packageName,
16645            final IPackageDataObserver observer) {
16646        final int userId = UserHandle.getCallingUserId();
16647        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
16648    }
16649
16650    @Override
16651    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
16652            final IPackageDataObserver observer) {
16653        mContext.enforceCallingOrSelfPermission(
16654                android.Manifest.permission.DELETE_CACHE_FILES, null);
16655        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16656                /* requireFullPermission= */ true, /* checkShell= */ false,
16657                "delete application cache files");
16658
16659        final PackageParser.Package pkg;
16660        synchronized (mPackages) {
16661            pkg = mPackages.get(packageName);
16662        }
16663
16664        // Queue up an async operation since the package deletion may take a little while.
16665        mHandler.post(new Runnable() {
16666            public void run() {
16667                synchronized (mInstallLock) {
16668                    final int flags = StorageManager.FLAG_STORAGE_DE
16669                            | StorageManager.FLAG_STORAGE_CE;
16670                    // We're only clearing cache files, so we don't care if the
16671                    // app is unfrozen and still able to run
16672                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
16673                    clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16674                }
16675                clearExternalStorageDataSync(packageName, userId, false);
16676                if (observer != null) {
16677                    try {
16678                        observer.onRemoveCompleted(packageName, true);
16679                    } catch (RemoteException e) {
16680                        Log.i(TAG, "Observer no longer exists.");
16681                    }
16682                }
16683            }
16684        });
16685    }
16686
16687    @Override
16688    public void getPackageSizeInfo(final String packageName, int userHandle,
16689            final IPackageStatsObserver observer) {
16690        mContext.enforceCallingOrSelfPermission(
16691                android.Manifest.permission.GET_PACKAGE_SIZE, null);
16692        if (packageName == null) {
16693            throw new IllegalArgumentException("Attempt to get size of null packageName");
16694        }
16695
16696        PackageStats stats = new PackageStats(packageName, userHandle);
16697
16698        /*
16699         * Queue up an async operation since the package measurement may take a
16700         * little while.
16701         */
16702        Message msg = mHandler.obtainMessage(INIT_COPY);
16703        msg.obj = new MeasureParams(stats, observer);
16704        mHandler.sendMessage(msg);
16705    }
16706
16707    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
16708        final PackageSetting ps;
16709        synchronized (mPackages) {
16710            ps = mSettings.mPackages.get(packageName);
16711            if (ps == null) {
16712                Slog.w(TAG, "Failed to find settings for " + packageName);
16713                return false;
16714            }
16715        }
16716        try {
16717            mInstaller.getAppSize(ps.volumeUuid, packageName, userId,
16718                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE,
16719                    ps.getCeDataInode(userId), ps.codePathString, stats);
16720        } catch (InstallerException e) {
16721            Slog.w(TAG, String.valueOf(e));
16722            return false;
16723        }
16724
16725        // For now, ignore code size of packages on system partition
16726        if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
16727            stats.codeSize = 0;
16728        }
16729
16730        return true;
16731    }
16732
16733    private int getUidTargetSdkVersionLockedLPr(int uid) {
16734        Object obj = mSettings.getUserIdLPr(uid);
16735        if (obj instanceof SharedUserSetting) {
16736            final SharedUserSetting sus = (SharedUserSetting) obj;
16737            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16738            final Iterator<PackageSetting> it = sus.packages.iterator();
16739            while (it.hasNext()) {
16740                final PackageSetting ps = it.next();
16741                if (ps.pkg != null) {
16742                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16743                    if (v < vers) vers = v;
16744                }
16745            }
16746            return vers;
16747        } else if (obj instanceof PackageSetting) {
16748            final PackageSetting ps = (PackageSetting) obj;
16749            if (ps.pkg != null) {
16750                return ps.pkg.applicationInfo.targetSdkVersion;
16751            }
16752        }
16753        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16754    }
16755
16756    @Override
16757    public void addPreferredActivity(IntentFilter filter, int match,
16758            ComponentName[] set, ComponentName activity, int userId) {
16759        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16760                "Adding preferred");
16761    }
16762
16763    private void addPreferredActivityInternal(IntentFilter filter, int match,
16764            ComponentName[] set, ComponentName activity, boolean always, int userId,
16765            String opname) {
16766        // writer
16767        int callingUid = Binder.getCallingUid();
16768        enforceCrossUserPermission(callingUid, userId,
16769                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16770        if (filter.countActions() == 0) {
16771            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16772            return;
16773        }
16774        synchronized (mPackages) {
16775            if (mContext.checkCallingOrSelfPermission(
16776                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16777                    != PackageManager.PERMISSION_GRANTED) {
16778                if (getUidTargetSdkVersionLockedLPr(callingUid)
16779                        < Build.VERSION_CODES.FROYO) {
16780                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16781                            + callingUid);
16782                    return;
16783                }
16784                mContext.enforceCallingOrSelfPermission(
16785                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16786            }
16787
16788            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16789            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16790                    + userId + ":");
16791            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16792            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16793            scheduleWritePackageRestrictionsLocked(userId);
16794        }
16795    }
16796
16797    @Override
16798    public void replacePreferredActivity(IntentFilter filter, int match,
16799            ComponentName[] set, ComponentName activity, int userId) {
16800        if (filter.countActions() != 1) {
16801            throw new IllegalArgumentException(
16802                    "replacePreferredActivity expects filter to have only 1 action.");
16803        }
16804        if (filter.countDataAuthorities() != 0
16805                || filter.countDataPaths() != 0
16806                || filter.countDataSchemes() > 1
16807                || filter.countDataTypes() != 0) {
16808            throw new IllegalArgumentException(
16809                    "replacePreferredActivity expects filter to have no data authorities, " +
16810                    "paths, or types; and at most one scheme.");
16811        }
16812
16813        final int callingUid = Binder.getCallingUid();
16814        enforceCrossUserPermission(callingUid, userId,
16815                true /* requireFullPermission */, false /* checkShell */,
16816                "replace preferred activity");
16817        synchronized (mPackages) {
16818            if (mContext.checkCallingOrSelfPermission(
16819                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16820                    != PackageManager.PERMISSION_GRANTED) {
16821                if (getUidTargetSdkVersionLockedLPr(callingUid)
16822                        < Build.VERSION_CODES.FROYO) {
16823                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16824                            + Binder.getCallingUid());
16825                    return;
16826                }
16827                mContext.enforceCallingOrSelfPermission(
16828                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16829            }
16830
16831            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16832            if (pir != null) {
16833                // Get all of the existing entries that exactly match this filter.
16834                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16835                if (existing != null && existing.size() == 1) {
16836                    PreferredActivity cur = existing.get(0);
16837                    if (DEBUG_PREFERRED) {
16838                        Slog.i(TAG, "Checking replace of preferred:");
16839                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16840                        if (!cur.mPref.mAlways) {
16841                            Slog.i(TAG, "  -- CUR; not mAlways!");
16842                        } else {
16843                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16844                            Slog.i(TAG, "  -- CUR: mSet="
16845                                    + Arrays.toString(cur.mPref.mSetComponents));
16846                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16847                            Slog.i(TAG, "  -- NEW: mMatch="
16848                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16849                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16850                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16851                        }
16852                    }
16853                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16854                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16855                            && cur.mPref.sameSet(set)) {
16856                        // Setting the preferred activity to what it happens to be already
16857                        if (DEBUG_PREFERRED) {
16858                            Slog.i(TAG, "Replacing with same preferred activity "
16859                                    + cur.mPref.mShortComponent + " for user "
16860                                    + userId + ":");
16861                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16862                        }
16863                        return;
16864                    }
16865                }
16866
16867                if (existing != null) {
16868                    if (DEBUG_PREFERRED) {
16869                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16870                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16871                    }
16872                    for (int i = 0; i < existing.size(); i++) {
16873                        PreferredActivity pa = existing.get(i);
16874                        if (DEBUG_PREFERRED) {
16875                            Slog.i(TAG, "Removing existing preferred activity "
16876                                    + pa.mPref.mComponent + ":");
16877                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16878                        }
16879                        pir.removeFilter(pa);
16880                    }
16881                }
16882            }
16883            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16884                    "Replacing preferred");
16885        }
16886    }
16887
16888    @Override
16889    public void clearPackagePreferredActivities(String packageName) {
16890        final int uid = Binder.getCallingUid();
16891        // writer
16892        synchronized (mPackages) {
16893            PackageParser.Package pkg = mPackages.get(packageName);
16894            if (pkg == null || pkg.applicationInfo.uid != uid) {
16895                if (mContext.checkCallingOrSelfPermission(
16896                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16897                        != PackageManager.PERMISSION_GRANTED) {
16898                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16899                            < Build.VERSION_CODES.FROYO) {
16900                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16901                                + Binder.getCallingUid());
16902                        return;
16903                    }
16904                    mContext.enforceCallingOrSelfPermission(
16905                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16906                }
16907            }
16908
16909            int user = UserHandle.getCallingUserId();
16910            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16911                scheduleWritePackageRestrictionsLocked(user);
16912            }
16913        }
16914    }
16915
16916    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16917    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16918        ArrayList<PreferredActivity> removed = null;
16919        boolean changed = false;
16920        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16921            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16922            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16923            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16924                continue;
16925            }
16926            Iterator<PreferredActivity> it = pir.filterIterator();
16927            while (it.hasNext()) {
16928                PreferredActivity pa = it.next();
16929                // Mark entry for removal only if it matches the package name
16930                // and the entry is of type "always".
16931                if (packageName == null ||
16932                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16933                                && pa.mPref.mAlways)) {
16934                    if (removed == null) {
16935                        removed = new ArrayList<PreferredActivity>();
16936                    }
16937                    removed.add(pa);
16938                }
16939            }
16940            if (removed != null) {
16941                for (int j=0; j<removed.size(); j++) {
16942                    PreferredActivity pa = removed.get(j);
16943                    pir.removeFilter(pa);
16944                }
16945                changed = true;
16946            }
16947        }
16948        return changed;
16949    }
16950
16951    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16952    private void clearIntentFilterVerificationsLPw(int userId) {
16953        final int packageCount = mPackages.size();
16954        for (int i = 0; i < packageCount; i++) {
16955            PackageParser.Package pkg = mPackages.valueAt(i);
16956            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16957        }
16958    }
16959
16960    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16961    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16962        if (userId == UserHandle.USER_ALL) {
16963            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16964                    sUserManager.getUserIds())) {
16965                for (int oneUserId : sUserManager.getUserIds()) {
16966                    scheduleWritePackageRestrictionsLocked(oneUserId);
16967                }
16968            }
16969        } else {
16970            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16971                scheduleWritePackageRestrictionsLocked(userId);
16972            }
16973        }
16974    }
16975
16976    void clearDefaultBrowserIfNeeded(String packageName) {
16977        for (int oneUserId : sUserManager.getUserIds()) {
16978            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16979            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16980            if (packageName.equals(defaultBrowserPackageName)) {
16981                setDefaultBrowserPackageName(null, oneUserId);
16982            }
16983        }
16984    }
16985
16986    @Override
16987    public void resetApplicationPreferences(int userId) {
16988        mContext.enforceCallingOrSelfPermission(
16989                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16990        final long identity = Binder.clearCallingIdentity();
16991        // writer
16992        try {
16993            synchronized (mPackages) {
16994                clearPackagePreferredActivitiesLPw(null, userId);
16995                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16996                // TODO: We have to reset the default SMS and Phone. This requires
16997                // significant refactoring to keep all default apps in the package
16998                // manager (cleaner but more work) or have the services provide
16999                // callbacks to the package manager to request a default app reset.
17000                applyFactoryDefaultBrowserLPw(userId);
17001                clearIntentFilterVerificationsLPw(userId);
17002                primeDomainVerificationsLPw(userId);
17003                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
17004                scheduleWritePackageRestrictionsLocked(userId);
17005            }
17006            resetNetworkPolicies(userId);
17007        } finally {
17008            Binder.restoreCallingIdentity(identity);
17009        }
17010    }
17011
17012    @Override
17013    public int getPreferredActivities(List<IntentFilter> outFilters,
17014            List<ComponentName> outActivities, String packageName) {
17015
17016        int num = 0;
17017        final int userId = UserHandle.getCallingUserId();
17018        // reader
17019        synchronized (mPackages) {
17020            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
17021            if (pir != null) {
17022                final Iterator<PreferredActivity> it = pir.filterIterator();
17023                while (it.hasNext()) {
17024                    final PreferredActivity pa = it.next();
17025                    if (packageName == null
17026                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
17027                                    && pa.mPref.mAlways)) {
17028                        if (outFilters != null) {
17029                            outFilters.add(new IntentFilter(pa));
17030                        }
17031                        if (outActivities != null) {
17032                            outActivities.add(pa.mPref.mComponent);
17033                        }
17034                    }
17035                }
17036            }
17037        }
17038
17039        return num;
17040    }
17041
17042    @Override
17043    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
17044            int userId) {
17045        int callingUid = Binder.getCallingUid();
17046        if (callingUid != Process.SYSTEM_UID) {
17047            throw new SecurityException(
17048                    "addPersistentPreferredActivity can only be run by the system");
17049        }
17050        if (filter.countActions() == 0) {
17051            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
17052            return;
17053        }
17054        synchronized (mPackages) {
17055            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
17056                    ":");
17057            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
17058            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
17059                    new PersistentPreferredActivity(filter, activity));
17060            scheduleWritePackageRestrictionsLocked(userId);
17061        }
17062    }
17063
17064    @Override
17065    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
17066        int callingUid = Binder.getCallingUid();
17067        if (callingUid != Process.SYSTEM_UID) {
17068            throw new SecurityException(
17069                    "clearPackagePersistentPreferredActivities can only be run by the system");
17070        }
17071        ArrayList<PersistentPreferredActivity> removed = null;
17072        boolean changed = false;
17073        synchronized (mPackages) {
17074            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
17075                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
17076                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
17077                        .valueAt(i);
17078                if (userId != thisUserId) {
17079                    continue;
17080                }
17081                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
17082                while (it.hasNext()) {
17083                    PersistentPreferredActivity ppa = it.next();
17084                    // Mark entry for removal only if it matches the package name.
17085                    if (ppa.mComponent.getPackageName().equals(packageName)) {
17086                        if (removed == null) {
17087                            removed = new ArrayList<PersistentPreferredActivity>();
17088                        }
17089                        removed.add(ppa);
17090                    }
17091                }
17092                if (removed != null) {
17093                    for (int j=0; j<removed.size(); j++) {
17094                        PersistentPreferredActivity ppa = removed.get(j);
17095                        ppir.removeFilter(ppa);
17096                    }
17097                    changed = true;
17098                }
17099            }
17100
17101            if (changed) {
17102                scheduleWritePackageRestrictionsLocked(userId);
17103            }
17104        }
17105    }
17106
17107    /**
17108     * Common machinery for picking apart a restored XML blob and passing
17109     * it to a caller-supplied functor to be applied to the running system.
17110     */
17111    private void restoreFromXml(XmlPullParser parser, int userId,
17112            String expectedStartTag, BlobXmlRestorer functor)
17113            throws IOException, XmlPullParserException {
17114        int type;
17115        while ((type = parser.next()) != XmlPullParser.START_TAG
17116                && type != XmlPullParser.END_DOCUMENT) {
17117        }
17118        if (type != XmlPullParser.START_TAG) {
17119            // oops didn't find a start tag?!
17120            if (DEBUG_BACKUP) {
17121                Slog.e(TAG, "Didn't find start tag during restore");
17122            }
17123            return;
17124        }
17125Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
17126        // this is supposed to be TAG_PREFERRED_BACKUP
17127        if (!expectedStartTag.equals(parser.getName())) {
17128            if (DEBUG_BACKUP) {
17129                Slog.e(TAG, "Found unexpected tag " + parser.getName());
17130            }
17131            return;
17132        }
17133
17134        // skip interfering stuff, then we're aligned with the backing implementation
17135        while ((type = parser.next()) == XmlPullParser.TEXT) { }
17136Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
17137        functor.apply(parser, userId);
17138    }
17139
17140    private interface BlobXmlRestorer {
17141        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
17142    }
17143
17144    /**
17145     * Non-Binder method, support for the backup/restore mechanism: write the
17146     * full set of preferred activities in its canonical XML format.  Returns the
17147     * XML output as a byte array, or null if there is none.
17148     */
17149    @Override
17150    public byte[] getPreferredActivityBackup(int userId) {
17151        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17152            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
17153        }
17154
17155        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17156        try {
17157            final XmlSerializer serializer = new FastXmlSerializer();
17158            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17159            serializer.startDocument(null, true);
17160            serializer.startTag(null, TAG_PREFERRED_BACKUP);
17161
17162            synchronized (mPackages) {
17163                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
17164            }
17165
17166            serializer.endTag(null, TAG_PREFERRED_BACKUP);
17167            serializer.endDocument();
17168            serializer.flush();
17169        } catch (Exception e) {
17170            if (DEBUG_BACKUP) {
17171                Slog.e(TAG, "Unable to write preferred activities for backup", e);
17172            }
17173            return null;
17174        }
17175
17176        return dataStream.toByteArray();
17177    }
17178
17179    @Override
17180    public void restorePreferredActivities(byte[] backup, int userId) {
17181        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17182            throw new SecurityException("Only the system may call restorePreferredActivities()");
17183        }
17184
17185        try {
17186            final XmlPullParser parser = Xml.newPullParser();
17187            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17188            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
17189                    new BlobXmlRestorer() {
17190                        @Override
17191                        public void apply(XmlPullParser parser, int userId)
17192                                throws XmlPullParserException, IOException {
17193                            synchronized (mPackages) {
17194                                mSettings.readPreferredActivitiesLPw(parser, userId);
17195                            }
17196                        }
17197                    } );
17198        } catch (Exception e) {
17199            if (DEBUG_BACKUP) {
17200                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17201            }
17202        }
17203    }
17204
17205    /**
17206     * Non-Binder method, support for the backup/restore mechanism: write the
17207     * default browser (etc) settings in its canonical XML format.  Returns the default
17208     * browser XML representation as a byte array, or null if there is none.
17209     */
17210    @Override
17211    public byte[] getDefaultAppsBackup(int userId) {
17212        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17213            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
17214        }
17215
17216        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17217        try {
17218            final XmlSerializer serializer = new FastXmlSerializer();
17219            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17220            serializer.startDocument(null, true);
17221            serializer.startTag(null, TAG_DEFAULT_APPS);
17222
17223            synchronized (mPackages) {
17224                mSettings.writeDefaultAppsLPr(serializer, userId);
17225            }
17226
17227            serializer.endTag(null, TAG_DEFAULT_APPS);
17228            serializer.endDocument();
17229            serializer.flush();
17230        } catch (Exception e) {
17231            if (DEBUG_BACKUP) {
17232                Slog.e(TAG, "Unable to write default apps for backup", e);
17233            }
17234            return null;
17235        }
17236
17237        return dataStream.toByteArray();
17238    }
17239
17240    @Override
17241    public void restoreDefaultApps(byte[] backup, int userId) {
17242        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17243            throw new SecurityException("Only the system may call restoreDefaultApps()");
17244        }
17245
17246        try {
17247            final XmlPullParser parser = Xml.newPullParser();
17248            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17249            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
17250                    new BlobXmlRestorer() {
17251                        @Override
17252                        public void apply(XmlPullParser parser, int userId)
17253                                throws XmlPullParserException, IOException {
17254                            synchronized (mPackages) {
17255                                mSettings.readDefaultAppsLPw(parser, userId);
17256                            }
17257                        }
17258                    } );
17259        } catch (Exception e) {
17260            if (DEBUG_BACKUP) {
17261                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
17262            }
17263        }
17264    }
17265
17266    @Override
17267    public byte[] getIntentFilterVerificationBackup(int userId) {
17268        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17269            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
17270        }
17271
17272        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17273        try {
17274            final XmlSerializer serializer = new FastXmlSerializer();
17275            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17276            serializer.startDocument(null, true);
17277            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
17278
17279            synchronized (mPackages) {
17280                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
17281            }
17282
17283            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
17284            serializer.endDocument();
17285            serializer.flush();
17286        } catch (Exception e) {
17287            if (DEBUG_BACKUP) {
17288                Slog.e(TAG, "Unable to write default apps for backup", e);
17289            }
17290            return null;
17291        }
17292
17293        return dataStream.toByteArray();
17294    }
17295
17296    @Override
17297    public void restoreIntentFilterVerification(byte[] backup, int userId) {
17298        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17299            throw new SecurityException("Only the system may call restorePreferredActivities()");
17300        }
17301
17302        try {
17303            final XmlPullParser parser = Xml.newPullParser();
17304            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17305            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
17306                    new BlobXmlRestorer() {
17307                        @Override
17308                        public void apply(XmlPullParser parser, int userId)
17309                                throws XmlPullParserException, IOException {
17310                            synchronized (mPackages) {
17311                                mSettings.readAllDomainVerificationsLPr(parser, userId);
17312                                mSettings.writeLPr();
17313                            }
17314                        }
17315                    } );
17316        } catch (Exception e) {
17317            if (DEBUG_BACKUP) {
17318                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17319            }
17320        }
17321    }
17322
17323    @Override
17324    public byte[] getPermissionGrantBackup(int userId) {
17325        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17326            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
17327        }
17328
17329        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
17330        try {
17331            final XmlSerializer serializer = new FastXmlSerializer();
17332            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
17333            serializer.startDocument(null, true);
17334            serializer.startTag(null, TAG_PERMISSION_BACKUP);
17335
17336            synchronized (mPackages) {
17337                serializeRuntimePermissionGrantsLPr(serializer, userId);
17338            }
17339
17340            serializer.endTag(null, TAG_PERMISSION_BACKUP);
17341            serializer.endDocument();
17342            serializer.flush();
17343        } catch (Exception e) {
17344            if (DEBUG_BACKUP) {
17345                Slog.e(TAG, "Unable to write default apps for backup", e);
17346            }
17347            return null;
17348        }
17349
17350        return dataStream.toByteArray();
17351    }
17352
17353    @Override
17354    public void restorePermissionGrants(byte[] backup, int userId) {
17355        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
17356            throw new SecurityException("Only the system may call restorePermissionGrants()");
17357        }
17358
17359        try {
17360            final XmlPullParser parser = Xml.newPullParser();
17361            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
17362            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
17363                    new BlobXmlRestorer() {
17364                        @Override
17365                        public void apply(XmlPullParser parser, int userId)
17366                                throws XmlPullParserException, IOException {
17367                            synchronized (mPackages) {
17368                                processRestoredPermissionGrantsLPr(parser, userId);
17369                            }
17370                        }
17371                    } );
17372        } catch (Exception e) {
17373            if (DEBUG_BACKUP) {
17374                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
17375            }
17376        }
17377    }
17378
17379    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
17380            throws IOException {
17381        serializer.startTag(null, TAG_ALL_GRANTS);
17382
17383        final int N = mSettings.mPackages.size();
17384        for (int i = 0; i < N; i++) {
17385            final PackageSetting ps = mSettings.mPackages.valueAt(i);
17386            boolean pkgGrantsKnown = false;
17387
17388            PermissionsState packagePerms = ps.getPermissionsState();
17389
17390            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
17391                final int grantFlags = state.getFlags();
17392                // only look at grants that are not system/policy fixed
17393                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
17394                    final boolean isGranted = state.isGranted();
17395                    // And only back up the user-twiddled state bits
17396                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
17397                        final String packageName = mSettings.mPackages.keyAt(i);
17398                        if (!pkgGrantsKnown) {
17399                            serializer.startTag(null, TAG_GRANT);
17400                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
17401                            pkgGrantsKnown = true;
17402                        }
17403
17404                        final boolean userSet =
17405                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
17406                        final boolean userFixed =
17407                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
17408                        final boolean revoke =
17409                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
17410
17411                        serializer.startTag(null, TAG_PERMISSION);
17412                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
17413                        if (isGranted) {
17414                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
17415                        }
17416                        if (userSet) {
17417                            serializer.attribute(null, ATTR_USER_SET, "true");
17418                        }
17419                        if (userFixed) {
17420                            serializer.attribute(null, ATTR_USER_FIXED, "true");
17421                        }
17422                        if (revoke) {
17423                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
17424                        }
17425                        serializer.endTag(null, TAG_PERMISSION);
17426                    }
17427                }
17428            }
17429
17430            if (pkgGrantsKnown) {
17431                serializer.endTag(null, TAG_GRANT);
17432            }
17433        }
17434
17435        serializer.endTag(null, TAG_ALL_GRANTS);
17436    }
17437
17438    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
17439            throws XmlPullParserException, IOException {
17440        String pkgName = null;
17441        int outerDepth = parser.getDepth();
17442        int type;
17443        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
17444                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
17445            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
17446                continue;
17447            }
17448
17449            final String tagName = parser.getName();
17450            if (tagName.equals(TAG_GRANT)) {
17451                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
17452                if (DEBUG_BACKUP) {
17453                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
17454                }
17455            } else if (tagName.equals(TAG_PERMISSION)) {
17456
17457                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
17458                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
17459
17460                int newFlagSet = 0;
17461                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
17462                    newFlagSet |= FLAG_PERMISSION_USER_SET;
17463                }
17464                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
17465                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
17466                }
17467                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
17468                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
17469                }
17470                if (DEBUG_BACKUP) {
17471                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
17472                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
17473                }
17474                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17475                if (ps != null) {
17476                    // Already installed so we apply the grant immediately
17477                    if (DEBUG_BACKUP) {
17478                        Slog.v(TAG, "        + already installed; applying");
17479                    }
17480                    PermissionsState perms = ps.getPermissionsState();
17481                    BasePermission bp = mSettings.mPermissions.get(permName);
17482                    if (bp != null) {
17483                        if (isGranted) {
17484                            perms.grantRuntimePermission(bp, userId);
17485                        }
17486                        if (newFlagSet != 0) {
17487                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
17488                        }
17489                    }
17490                } else {
17491                    // Need to wait for post-restore install to apply the grant
17492                    if (DEBUG_BACKUP) {
17493                        Slog.v(TAG, "        - not yet installed; saving for later");
17494                    }
17495                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
17496                            isGranted, newFlagSet, userId);
17497                }
17498            } else {
17499                PackageManagerService.reportSettingsProblem(Log.WARN,
17500                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
17501                XmlUtils.skipCurrentTag(parser);
17502            }
17503        }
17504
17505        scheduleWriteSettingsLocked();
17506        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
17507    }
17508
17509    @Override
17510    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
17511            int sourceUserId, int targetUserId, int flags) {
17512        mContext.enforceCallingOrSelfPermission(
17513                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17514        int callingUid = Binder.getCallingUid();
17515        enforceOwnerRights(ownerPackage, callingUid);
17516        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17517        if (intentFilter.countActions() == 0) {
17518            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
17519            return;
17520        }
17521        synchronized (mPackages) {
17522            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
17523                    ownerPackage, targetUserId, flags);
17524            CrossProfileIntentResolver resolver =
17525                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17526            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
17527            // We have all those whose filter is equal. Now checking if the rest is equal as well.
17528            if (existing != null) {
17529                int size = existing.size();
17530                for (int i = 0; i < size; i++) {
17531                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
17532                        return;
17533                    }
17534                }
17535            }
17536            resolver.addFilter(newFilter);
17537            scheduleWritePackageRestrictionsLocked(sourceUserId);
17538        }
17539    }
17540
17541    @Override
17542    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
17543        mContext.enforceCallingOrSelfPermission(
17544                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
17545        int callingUid = Binder.getCallingUid();
17546        enforceOwnerRights(ownerPackage, callingUid);
17547        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
17548        synchronized (mPackages) {
17549            CrossProfileIntentResolver resolver =
17550                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
17551            ArraySet<CrossProfileIntentFilter> set =
17552                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
17553            for (CrossProfileIntentFilter filter : set) {
17554                if (filter.getOwnerPackage().equals(ownerPackage)) {
17555                    resolver.removeFilter(filter);
17556                }
17557            }
17558            scheduleWritePackageRestrictionsLocked(sourceUserId);
17559        }
17560    }
17561
17562    // Enforcing that callingUid is owning pkg on userId
17563    private void enforceOwnerRights(String pkg, int callingUid) {
17564        // The system owns everything.
17565        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17566            return;
17567        }
17568        int callingUserId = UserHandle.getUserId(callingUid);
17569        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
17570        if (pi == null) {
17571            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
17572                    + callingUserId);
17573        }
17574        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
17575            throw new SecurityException("Calling uid " + callingUid
17576                    + " does not own package " + pkg);
17577        }
17578    }
17579
17580    @Override
17581    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
17582        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
17583    }
17584
17585    private Intent getHomeIntent() {
17586        Intent intent = new Intent(Intent.ACTION_MAIN);
17587        intent.addCategory(Intent.CATEGORY_HOME);
17588        return intent;
17589    }
17590
17591    private IntentFilter getHomeFilter() {
17592        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
17593        filter.addCategory(Intent.CATEGORY_HOME);
17594        filter.addCategory(Intent.CATEGORY_DEFAULT);
17595        return filter;
17596    }
17597
17598    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
17599            int userId) {
17600        Intent intent  = getHomeIntent();
17601        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
17602                PackageManager.GET_META_DATA, userId);
17603        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
17604                true, false, false, userId);
17605
17606        allHomeCandidates.clear();
17607        if (list != null) {
17608            for (ResolveInfo ri : list) {
17609                allHomeCandidates.add(ri);
17610            }
17611        }
17612        return (preferred == null || preferred.activityInfo == null)
17613                ? null
17614                : new ComponentName(preferred.activityInfo.packageName,
17615                        preferred.activityInfo.name);
17616    }
17617
17618    @Override
17619    public void setHomeActivity(ComponentName comp, int userId) {
17620        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
17621        getHomeActivitiesAsUser(homeActivities, userId);
17622
17623        boolean found = false;
17624
17625        final int size = homeActivities.size();
17626        final ComponentName[] set = new ComponentName[size];
17627        for (int i = 0; i < size; i++) {
17628            final ResolveInfo candidate = homeActivities.get(i);
17629            final ActivityInfo info = candidate.activityInfo;
17630            final ComponentName activityName = new ComponentName(info.packageName, info.name);
17631            set[i] = activityName;
17632            if (!found && activityName.equals(comp)) {
17633                found = true;
17634            }
17635        }
17636        if (!found) {
17637            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
17638                    + userId);
17639        }
17640        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
17641                set, comp, userId);
17642    }
17643
17644    private @Nullable String getSetupWizardPackageName() {
17645        final Intent intent = new Intent(Intent.ACTION_MAIN);
17646        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
17647
17648        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17649                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
17650                        | MATCH_DISABLED_COMPONENTS,
17651                UserHandle.myUserId());
17652        if (matches.size() == 1) {
17653            return matches.get(0).getComponentInfo().packageName;
17654        } else {
17655            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17656                    + ": matches=" + matches);
17657            return null;
17658        }
17659    }
17660
17661    @Override
17662    public void setApplicationEnabledSetting(String appPackageName,
17663            int newState, int flags, int userId, String callingPackage) {
17664        if (!sUserManager.exists(userId)) return;
17665        if (callingPackage == null) {
17666            callingPackage = Integer.toString(Binder.getCallingUid());
17667        }
17668        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17669    }
17670
17671    @Override
17672    public void setComponentEnabledSetting(ComponentName componentName,
17673            int newState, int flags, int userId) {
17674        if (!sUserManager.exists(userId)) return;
17675        setEnabledSetting(componentName.getPackageName(),
17676                componentName.getClassName(), newState, flags, userId, null);
17677    }
17678
17679    private void setEnabledSetting(final String packageName, String className, int newState,
17680            final int flags, int userId, String callingPackage) {
17681        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17682              || newState == COMPONENT_ENABLED_STATE_ENABLED
17683              || newState == COMPONENT_ENABLED_STATE_DISABLED
17684              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17685              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17686            throw new IllegalArgumentException("Invalid new component state: "
17687                    + newState);
17688        }
17689        PackageSetting pkgSetting;
17690        final int uid = Binder.getCallingUid();
17691        final int permission;
17692        if (uid == Process.SYSTEM_UID) {
17693            permission = PackageManager.PERMISSION_GRANTED;
17694        } else {
17695            permission = mContext.checkCallingOrSelfPermission(
17696                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17697        }
17698        enforceCrossUserPermission(uid, userId,
17699                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17700        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17701        boolean sendNow = false;
17702        boolean isApp = (className == null);
17703        String componentName = isApp ? packageName : className;
17704        int packageUid = -1;
17705        ArrayList<String> components;
17706
17707        // writer
17708        synchronized (mPackages) {
17709            pkgSetting = mSettings.mPackages.get(packageName);
17710            if (pkgSetting == null) {
17711                if (className == null) {
17712                    throw new IllegalArgumentException("Unknown package: " + packageName);
17713                }
17714                throw new IllegalArgumentException(
17715                        "Unknown component: " + packageName + "/" + className);
17716            }
17717        }
17718
17719        // Limit who can change which apps
17720        if (!UserHandle.isSameApp(uid, pkgSetting.appId)) {
17721            // Don't allow apps that don't have permission to modify other apps
17722            if (!allowedByPermission) {
17723                throw new SecurityException(
17724                        "Permission Denial: attempt to change component state from pid="
17725                        + Binder.getCallingPid()
17726                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17727            }
17728            // Don't allow changing profile and device owners. Calling into DPMS, so no locking.
17729            final DevicePolicyManagerInternal dpmi = LocalServices
17730                    .getService(DevicePolicyManagerInternal.class);
17731            if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
17732                throw new SecurityException("Cannot disable a device owner or a profile owner");
17733            }
17734        }
17735
17736        synchronized (mPackages) {
17737            if (uid == Process.SHELL_UID) {
17738                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17739                int oldState = pkgSetting.getEnabled(userId);
17740                if (className == null
17741                    &&
17742                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17743                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17744                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17745                    &&
17746                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17747                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17748                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17749                    // ok
17750                } else {
17751                    throw new SecurityException(
17752                            "Shell cannot change component state for " + packageName + "/"
17753                            + className + " to " + newState);
17754                }
17755            }
17756            if (className == null) {
17757                // We're dealing with an application/package level state change
17758                if (pkgSetting.getEnabled(userId) == newState) {
17759                    // Nothing to do
17760                    return;
17761                }
17762                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17763                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17764                    // Don't care about who enables an app.
17765                    callingPackage = null;
17766                }
17767                pkgSetting.setEnabled(newState, userId, callingPackage);
17768                // pkgSetting.pkg.mSetEnabled = newState;
17769            } else {
17770                // We're dealing with a component level state change
17771                // First, verify that this is a valid class name.
17772                PackageParser.Package pkg = pkgSetting.pkg;
17773                if (pkg == null || !pkg.hasComponentClassName(className)) {
17774                    if (pkg != null &&
17775                            pkg.applicationInfo.targetSdkVersion >=
17776                                    Build.VERSION_CODES.JELLY_BEAN) {
17777                        throw new IllegalArgumentException("Component class " + className
17778                                + " does not exist in " + packageName);
17779                    } else {
17780                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17781                                + className + " does not exist in " + packageName);
17782                    }
17783                }
17784                switch (newState) {
17785                case COMPONENT_ENABLED_STATE_ENABLED:
17786                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17787                        return;
17788                    }
17789                    break;
17790                case COMPONENT_ENABLED_STATE_DISABLED:
17791                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17792                        return;
17793                    }
17794                    break;
17795                case COMPONENT_ENABLED_STATE_DEFAULT:
17796                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17797                        return;
17798                    }
17799                    break;
17800                default:
17801                    Slog.e(TAG, "Invalid new component state: " + newState);
17802                    return;
17803                }
17804            }
17805            scheduleWritePackageRestrictionsLocked(userId);
17806            components = mPendingBroadcasts.get(userId, packageName);
17807            final boolean newPackage = components == null;
17808            if (newPackage) {
17809                components = new ArrayList<String>();
17810            }
17811            if (!components.contains(componentName)) {
17812                components.add(componentName);
17813            }
17814            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17815                sendNow = true;
17816                // Purge entry from pending broadcast list if another one exists already
17817                // since we are sending one right away.
17818                mPendingBroadcasts.remove(userId, packageName);
17819            } else {
17820                if (newPackage) {
17821                    mPendingBroadcasts.put(userId, packageName, components);
17822                }
17823                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17824                    // Schedule a message
17825                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17826                }
17827            }
17828        }
17829
17830        long callingId = Binder.clearCallingIdentity();
17831        try {
17832            if (sendNow) {
17833                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17834                sendPackageChangedBroadcast(packageName,
17835                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17836            }
17837        } finally {
17838            Binder.restoreCallingIdentity(callingId);
17839        }
17840    }
17841
17842    @Override
17843    public void flushPackageRestrictionsAsUser(int userId) {
17844        if (!sUserManager.exists(userId)) {
17845            return;
17846        }
17847        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17848                false /* checkShell */, "flushPackageRestrictions");
17849        synchronized (mPackages) {
17850            mSettings.writePackageRestrictionsLPr(userId);
17851            mDirtyUsers.remove(userId);
17852            if (mDirtyUsers.isEmpty()) {
17853                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17854            }
17855        }
17856    }
17857
17858    private void sendPackageChangedBroadcast(String packageName,
17859            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17860        if (DEBUG_INSTALL)
17861            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17862                    + componentNames);
17863        Bundle extras = new Bundle(4);
17864        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17865        String nameList[] = new String[componentNames.size()];
17866        componentNames.toArray(nameList);
17867        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17868        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17869        extras.putInt(Intent.EXTRA_UID, packageUid);
17870        // If this is not reporting a change of the overall package, then only send it
17871        // to registered receivers.  We don't want to launch a swath of apps for every
17872        // little component state change.
17873        final int flags = !componentNames.contains(packageName)
17874                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17875        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17876                new int[] {UserHandle.getUserId(packageUid)});
17877    }
17878
17879    @Override
17880    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17881        if (!sUserManager.exists(userId)) return;
17882        final int uid = Binder.getCallingUid();
17883        final int permission = mContext.checkCallingOrSelfPermission(
17884                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17885        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17886        enforceCrossUserPermission(uid, userId,
17887                true /* requireFullPermission */, true /* checkShell */, "stop package");
17888        // writer
17889        synchronized (mPackages) {
17890            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17891                    allowedByPermission, uid, userId)) {
17892                scheduleWritePackageRestrictionsLocked(userId);
17893            }
17894        }
17895    }
17896
17897    @Override
17898    public String getInstallerPackageName(String packageName) {
17899        // reader
17900        synchronized (mPackages) {
17901            return mSettings.getInstallerPackageNameLPr(packageName);
17902        }
17903    }
17904
17905    public boolean isOrphaned(String packageName) {
17906        // reader
17907        synchronized (mPackages) {
17908            return mSettings.isOrphaned(packageName);
17909        }
17910    }
17911
17912    @Override
17913    public int getApplicationEnabledSetting(String packageName, int userId) {
17914        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17915        int uid = Binder.getCallingUid();
17916        enforceCrossUserPermission(uid, userId,
17917                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17918        // reader
17919        synchronized (mPackages) {
17920            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17921        }
17922    }
17923
17924    @Override
17925    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17926        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17927        int uid = Binder.getCallingUid();
17928        enforceCrossUserPermission(uid, userId,
17929                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17930        // reader
17931        synchronized (mPackages) {
17932            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17933        }
17934    }
17935
17936    @Override
17937    public void enterSafeMode() {
17938        enforceSystemOrRoot("Only the system can request entering safe mode");
17939
17940        if (!mSystemReady) {
17941            mSafeMode = true;
17942        }
17943    }
17944
17945    @Override
17946    public void systemReady() {
17947        mSystemReady = true;
17948
17949        // Read the compatibilty setting when the system is ready.
17950        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17951                mContext.getContentResolver(),
17952                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17953        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17954        if (DEBUG_SETTINGS) {
17955            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17956        }
17957
17958        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17959
17960        synchronized (mPackages) {
17961            // Verify that all of the preferred activity components actually
17962            // exist.  It is possible for applications to be updated and at
17963            // that point remove a previously declared activity component that
17964            // had been set as a preferred activity.  We try to clean this up
17965            // the next time we encounter that preferred activity, but it is
17966            // possible for the user flow to never be able to return to that
17967            // situation so here we do a sanity check to make sure we haven't
17968            // left any junk around.
17969            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17970            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17971                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17972                removed.clear();
17973                for (PreferredActivity pa : pir.filterSet()) {
17974                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17975                        removed.add(pa);
17976                    }
17977                }
17978                if (removed.size() > 0) {
17979                    for (int r=0; r<removed.size(); r++) {
17980                        PreferredActivity pa = removed.get(r);
17981                        Slog.w(TAG, "Removing dangling preferred activity: "
17982                                + pa.mPref.mComponent);
17983                        pir.removeFilter(pa);
17984                    }
17985                    mSettings.writePackageRestrictionsLPr(
17986                            mSettings.mPreferredActivities.keyAt(i));
17987                }
17988            }
17989
17990            for (int userId : UserManagerService.getInstance().getUserIds()) {
17991                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17992                    grantPermissionsUserIds = ArrayUtils.appendInt(
17993                            grantPermissionsUserIds, userId);
17994                }
17995            }
17996        }
17997        sUserManager.systemReady();
17998
17999        // If we upgraded grant all default permissions before kicking off.
18000        for (int userId : grantPermissionsUserIds) {
18001            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18002        }
18003
18004        // Kick off any messages waiting for system ready
18005        if (mPostSystemReadyMessages != null) {
18006            for (Message msg : mPostSystemReadyMessages) {
18007                msg.sendToTarget();
18008            }
18009            mPostSystemReadyMessages = null;
18010        }
18011
18012        // Watch for external volumes that come and go over time
18013        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18014        storage.registerListener(mStorageListener);
18015
18016        mInstallerService.systemReady();
18017        mPackageDexOptimizer.systemReady();
18018
18019        MountServiceInternal mountServiceInternal = LocalServices.getService(
18020                MountServiceInternal.class);
18021        mountServiceInternal.addExternalStoragePolicy(
18022                new MountServiceInternal.ExternalStorageMountPolicy() {
18023            @Override
18024            public int getMountMode(int uid, String packageName) {
18025                if (Process.isIsolated(uid)) {
18026                    return Zygote.MOUNT_EXTERNAL_NONE;
18027                }
18028                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18029                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18030                }
18031                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18032                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18033                }
18034                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18035                    return Zygote.MOUNT_EXTERNAL_READ;
18036                }
18037                return Zygote.MOUNT_EXTERNAL_WRITE;
18038            }
18039
18040            @Override
18041            public boolean hasExternalStorage(int uid, String packageName) {
18042                return true;
18043            }
18044        });
18045
18046        // Now that we're mostly running, clean up stale users and apps
18047        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18048        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18049    }
18050
18051    @Override
18052    public boolean isSafeMode() {
18053        return mSafeMode;
18054    }
18055
18056    @Override
18057    public boolean hasSystemUidErrors() {
18058        return mHasSystemUidErrors;
18059    }
18060
18061    static String arrayToString(int[] array) {
18062        StringBuffer buf = new StringBuffer(128);
18063        buf.append('[');
18064        if (array != null) {
18065            for (int i=0; i<array.length; i++) {
18066                if (i > 0) buf.append(", ");
18067                buf.append(array[i]);
18068            }
18069        }
18070        buf.append(']');
18071        return buf.toString();
18072    }
18073
18074    static class DumpState {
18075        public static final int DUMP_LIBS = 1 << 0;
18076        public static final int DUMP_FEATURES = 1 << 1;
18077        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18078        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18079        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18080        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18081        public static final int DUMP_PERMISSIONS = 1 << 6;
18082        public static final int DUMP_PACKAGES = 1 << 7;
18083        public static final int DUMP_SHARED_USERS = 1 << 8;
18084        public static final int DUMP_MESSAGES = 1 << 9;
18085        public static final int DUMP_PROVIDERS = 1 << 10;
18086        public static final int DUMP_VERIFIERS = 1 << 11;
18087        public static final int DUMP_PREFERRED = 1 << 12;
18088        public static final int DUMP_PREFERRED_XML = 1 << 13;
18089        public static final int DUMP_KEYSETS = 1 << 14;
18090        public static final int DUMP_VERSION = 1 << 15;
18091        public static final int DUMP_INSTALLS = 1 << 16;
18092        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18093        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18094        public static final int DUMP_FROZEN = 1 << 19;
18095        public static final int DUMP_DEXOPT = 1 << 20;
18096
18097        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18098
18099        private int mTypes;
18100
18101        private int mOptions;
18102
18103        private boolean mTitlePrinted;
18104
18105        private SharedUserSetting mSharedUser;
18106
18107        public boolean isDumping(int type) {
18108            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18109                return true;
18110            }
18111
18112            return (mTypes & type) != 0;
18113        }
18114
18115        public void setDump(int type) {
18116            mTypes |= type;
18117        }
18118
18119        public boolean isOptionEnabled(int option) {
18120            return (mOptions & option) != 0;
18121        }
18122
18123        public void setOptionEnabled(int option) {
18124            mOptions |= option;
18125        }
18126
18127        public boolean onTitlePrinted() {
18128            final boolean printed = mTitlePrinted;
18129            mTitlePrinted = true;
18130            return printed;
18131        }
18132
18133        public boolean getTitlePrinted() {
18134            return mTitlePrinted;
18135        }
18136
18137        public void setTitlePrinted(boolean enabled) {
18138            mTitlePrinted = enabled;
18139        }
18140
18141        public SharedUserSetting getSharedUser() {
18142            return mSharedUser;
18143        }
18144
18145        public void setSharedUser(SharedUserSetting user) {
18146            mSharedUser = user;
18147        }
18148    }
18149
18150    @Override
18151    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18152            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18153        (new PackageManagerShellCommand(this)).exec(
18154                this, in, out, err, args, resultReceiver);
18155    }
18156
18157    @Override
18158    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18159        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18160                != PackageManager.PERMISSION_GRANTED) {
18161            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18162                    + Binder.getCallingPid()
18163                    + ", uid=" + Binder.getCallingUid()
18164                    + " without permission "
18165                    + android.Manifest.permission.DUMP);
18166            return;
18167        }
18168
18169        DumpState dumpState = new DumpState();
18170        boolean fullPreferred = false;
18171        boolean checkin = false;
18172
18173        String packageName = null;
18174        ArraySet<String> permissionNames = null;
18175
18176        int opti = 0;
18177        while (opti < args.length) {
18178            String opt = args[opti];
18179            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18180                break;
18181            }
18182            opti++;
18183
18184            if ("-a".equals(opt)) {
18185                // Right now we only know how to print all.
18186            } else if ("-h".equals(opt)) {
18187                pw.println("Package manager dump options:");
18188                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18189                pw.println("    --checkin: dump for a checkin");
18190                pw.println("    -f: print details of intent filters");
18191                pw.println("    -h: print this help");
18192                pw.println("  cmd may be one of:");
18193                pw.println("    l[ibraries]: list known shared libraries");
18194                pw.println("    f[eatures]: list device features");
18195                pw.println("    k[eysets]: print known keysets");
18196                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18197                pw.println("    perm[issions]: dump permissions");
18198                pw.println("    permission [name ...]: dump declaration and use of given permission");
18199                pw.println("    pref[erred]: print preferred package settings");
18200                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18201                pw.println("    prov[iders]: dump content providers");
18202                pw.println("    p[ackages]: dump installed packages");
18203                pw.println("    s[hared-users]: dump shared user IDs");
18204                pw.println("    m[essages]: print collected runtime messages");
18205                pw.println("    v[erifiers]: print package verifier info");
18206                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18207                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18208                pw.println("    version: print database version info");
18209                pw.println("    write: write current settings now");
18210                pw.println("    installs: details about install sessions");
18211                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18212                pw.println("    dexopt: dump dexopt state");
18213                pw.println("    <package.name>: info about given package");
18214                return;
18215            } else if ("--checkin".equals(opt)) {
18216                checkin = true;
18217            } else if ("-f".equals(opt)) {
18218                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18219            } else {
18220                pw.println("Unknown argument: " + opt + "; use -h for help");
18221            }
18222        }
18223
18224        // Is the caller requesting to dump a particular piece of data?
18225        if (opti < args.length) {
18226            String cmd = args[opti];
18227            opti++;
18228            // Is this a package name?
18229            if ("android".equals(cmd) || cmd.contains(".")) {
18230                packageName = cmd;
18231                // When dumping a single package, we always dump all of its
18232                // filter information since the amount of data will be reasonable.
18233                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18234            } else if ("check-permission".equals(cmd)) {
18235                if (opti >= args.length) {
18236                    pw.println("Error: check-permission missing permission argument");
18237                    return;
18238                }
18239                String perm = args[opti];
18240                opti++;
18241                if (opti >= args.length) {
18242                    pw.println("Error: check-permission missing package argument");
18243                    return;
18244                }
18245                String pkg = args[opti];
18246                opti++;
18247                int user = UserHandle.getUserId(Binder.getCallingUid());
18248                if (opti < args.length) {
18249                    try {
18250                        user = Integer.parseInt(args[opti]);
18251                    } catch (NumberFormatException e) {
18252                        pw.println("Error: check-permission user argument is not a number: "
18253                                + args[opti]);
18254                        return;
18255                    }
18256                }
18257                pw.println(checkPermission(perm, pkg, user));
18258                return;
18259            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18260                dumpState.setDump(DumpState.DUMP_LIBS);
18261            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18262                dumpState.setDump(DumpState.DUMP_FEATURES);
18263            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18264                if (opti >= args.length) {
18265                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18266                            | DumpState.DUMP_SERVICE_RESOLVERS
18267                            | DumpState.DUMP_RECEIVER_RESOLVERS
18268                            | DumpState.DUMP_CONTENT_RESOLVERS);
18269                } else {
18270                    while (opti < args.length) {
18271                        String name = args[opti];
18272                        if ("a".equals(name) || "activity".equals(name)) {
18273                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18274                        } else if ("s".equals(name) || "service".equals(name)) {
18275                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18276                        } else if ("r".equals(name) || "receiver".equals(name)) {
18277                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18278                        } else if ("c".equals(name) || "content".equals(name)) {
18279                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18280                        } else {
18281                            pw.println("Error: unknown resolver table type: " + name);
18282                            return;
18283                        }
18284                        opti++;
18285                    }
18286                }
18287            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18288                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18289            } else if ("permission".equals(cmd)) {
18290                if (opti >= args.length) {
18291                    pw.println("Error: permission requires permission name");
18292                    return;
18293                }
18294                permissionNames = new ArraySet<>();
18295                while (opti < args.length) {
18296                    permissionNames.add(args[opti]);
18297                    opti++;
18298                }
18299                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18300                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18301            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18302                dumpState.setDump(DumpState.DUMP_PREFERRED);
18303            } else if ("preferred-xml".equals(cmd)) {
18304                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18305                if (opti < args.length && "--full".equals(args[opti])) {
18306                    fullPreferred = true;
18307                    opti++;
18308                }
18309            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18310                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18311            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18312                dumpState.setDump(DumpState.DUMP_PACKAGES);
18313            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18314                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18315            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18316                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18317            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18318                dumpState.setDump(DumpState.DUMP_MESSAGES);
18319            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18320                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18321            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18322                    || "intent-filter-verifiers".equals(cmd)) {
18323                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18324            } else if ("version".equals(cmd)) {
18325                dumpState.setDump(DumpState.DUMP_VERSION);
18326            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18327                dumpState.setDump(DumpState.DUMP_KEYSETS);
18328            } else if ("installs".equals(cmd)) {
18329                dumpState.setDump(DumpState.DUMP_INSTALLS);
18330            } else if ("frozen".equals(cmd)) {
18331                dumpState.setDump(DumpState.DUMP_FROZEN);
18332            } else if ("dexopt".equals(cmd)) {
18333                dumpState.setDump(DumpState.DUMP_DEXOPT);
18334            } else if ("write".equals(cmd)) {
18335                synchronized (mPackages) {
18336                    mSettings.writeLPr();
18337                    pw.println("Settings written.");
18338                    return;
18339                }
18340            }
18341        }
18342
18343        if (checkin) {
18344            pw.println("vers,1");
18345        }
18346
18347        // reader
18348        synchronized (mPackages) {
18349            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18350                if (!checkin) {
18351                    if (dumpState.onTitlePrinted())
18352                        pw.println();
18353                    pw.println("Database versions:");
18354                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18355                }
18356            }
18357
18358            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18359                if (!checkin) {
18360                    if (dumpState.onTitlePrinted())
18361                        pw.println();
18362                    pw.println("Verifiers:");
18363                    pw.print("  Required: ");
18364                    pw.print(mRequiredVerifierPackage);
18365                    pw.print(" (uid=");
18366                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18367                            UserHandle.USER_SYSTEM));
18368                    pw.println(")");
18369                } else if (mRequiredVerifierPackage != null) {
18370                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18371                    pw.print(",");
18372                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18373                            UserHandle.USER_SYSTEM));
18374                }
18375            }
18376
18377            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18378                    packageName == null) {
18379                if (mIntentFilterVerifierComponent != null) {
18380                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18381                    if (!checkin) {
18382                        if (dumpState.onTitlePrinted())
18383                            pw.println();
18384                        pw.println("Intent Filter Verifier:");
18385                        pw.print("  Using: ");
18386                        pw.print(verifierPackageName);
18387                        pw.print(" (uid=");
18388                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18389                                UserHandle.USER_SYSTEM));
18390                        pw.println(")");
18391                    } else if (verifierPackageName != null) {
18392                        pw.print("ifv,"); pw.print(verifierPackageName);
18393                        pw.print(",");
18394                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18395                                UserHandle.USER_SYSTEM));
18396                    }
18397                } else {
18398                    pw.println();
18399                    pw.println("No Intent Filter Verifier available!");
18400                }
18401            }
18402
18403            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18404                boolean printedHeader = false;
18405                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18406                while (it.hasNext()) {
18407                    String name = it.next();
18408                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18409                    if (!checkin) {
18410                        if (!printedHeader) {
18411                            if (dumpState.onTitlePrinted())
18412                                pw.println();
18413                            pw.println("Libraries:");
18414                            printedHeader = true;
18415                        }
18416                        pw.print("  ");
18417                    } else {
18418                        pw.print("lib,");
18419                    }
18420                    pw.print(name);
18421                    if (!checkin) {
18422                        pw.print(" -> ");
18423                    }
18424                    if (ent.path != null) {
18425                        if (!checkin) {
18426                            pw.print("(jar) ");
18427                            pw.print(ent.path);
18428                        } else {
18429                            pw.print(",jar,");
18430                            pw.print(ent.path);
18431                        }
18432                    } else {
18433                        if (!checkin) {
18434                            pw.print("(apk) ");
18435                            pw.print(ent.apk);
18436                        } else {
18437                            pw.print(",apk,");
18438                            pw.print(ent.apk);
18439                        }
18440                    }
18441                    pw.println();
18442                }
18443            }
18444
18445            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18446                if (dumpState.onTitlePrinted())
18447                    pw.println();
18448                if (!checkin) {
18449                    pw.println("Features:");
18450                }
18451
18452                for (FeatureInfo feat : mAvailableFeatures.values()) {
18453                    if (checkin) {
18454                        pw.print("feat,");
18455                        pw.print(feat.name);
18456                        pw.print(",");
18457                        pw.println(feat.version);
18458                    } else {
18459                        pw.print("  ");
18460                        pw.print(feat.name);
18461                        if (feat.version > 0) {
18462                            pw.print(" version=");
18463                            pw.print(feat.version);
18464                        }
18465                        pw.println();
18466                    }
18467                }
18468            }
18469
18470            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18471                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18472                        : "Activity Resolver Table:", "  ", packageName,
18473                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18474                    dumpState.setTitlePrinted(true);
18475                }
18476            }
18477            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18478                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18479                        : "Receiver Resolver Table:", "  ", packageName,
18480                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18481                    dumpState.setTitlePrinted(true);
18482                }
18483            }
18484            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18485                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18486                        : "Service Resolver Table:", "  ", packageName,
18487                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18488                    dumpState.setTitlePrinted(true);
18489                }
18490            }
18491            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18492                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18493                        : "Provider Resolver Table:", "  ", packageName,
18494                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18495                    dumpState.setTitlePrinted(true);
18496                }
18497            }
18498
18499            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18500                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18501                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18502                    int user = mSettings.mPreferredActivities.keyAt(i);
18503                    if (pir.dump(pw,
18504                            dumpState.getTitlePrinted()
18505                                ? "\nPreferred Activities User " + user + ":"
18506                                : "Preferred Activities User " + user + ":", "  ",
18507                            packageName, true, false)) {
18508                        dumpState.setTitlePrinted(true);
18509                    }
18510                }
18511            }
18512
18513            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18514                pw.flush();
18515                FileOutputStream fout = new FileOutputStream(fd);
18516                BufferedOutputStream str = new BufferedOutputStream(fout);
18517                XmlSerializer serializer = new FastXmlSerializer();
18518                try {
18519                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18520                    serializer.startDocument(null, true);
18521                    serializer.setFeature(
18522                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18523                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18524                    serializer.endDocument();
18525                    serializer.flush();
18526                } catch (IllegalArgumentException e) {
18527                    pw.println("Failed writing: " + e);
18528                } catch (IllegalStateException e) {
18529                    pw.println("Failed writing: " + e);
18530                } catch (IOException e) {
18531                    pw.println("Failed writing: " + e);
18532                }
18533            }
18534
18535            if (!checkin
18536                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18537                    && packageName == null) {
18538                pw.println();
18539                int count = mSettings.mPackages.size();
18540                if (count == 0) {
18541                    pw.println("No applications!");
18542                    pw.println();
18543                } else {
18544                    final String prefix = "  ";
18545                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18546                    if (allPackageSettings.size() == 0) {
18547                        pw.println("No domain preferred apps!");
18548                        pw.println();
18549                    } else {
18550                        pw.println("App verification status:");
18551                        pw.println();
18552                        count = 0;
18553                        for (PackageSetting ps : allPackageSettings) {
18554                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18555                            if (ivi == null || ivi.getPackageName() == null) continue;
18556                            pw.println(prefix + "Package: " + ivi.getPackageName());
18557                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18558                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18559                            pw.println();
18560                            count++;
18561                        }
18562                        if (count == 0) {
18563                            pw.println(prefix + "No app verification established.");
18564                            pw.println();
18565                        }
18566                        for (int userId : sUserManager.getUserIds()) {
18567                            pw.println("App linkages for user " + userId + ":");
18568                            pw.println();
18569                            count = 0;
18570                            for (PackageSetting ps : allPackageSettings) {
18571                                final long status = ps.getDomainVerificationStatusForUser(userId);
18572                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18573                                    continue;
18574                                }
18575                                pw.println(prefix + "Package: " + ps.name);
18576                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18577                                String statusStr = IntentFilterVerificationInfo.
18578                                        getStatusStringFromValue(status);
18579                                pw.println(prefix + "Status:  " + statusStr);
18580                                pw.println();
18581                                count++;
18582                            }
18583                            if (count == 0) {
18584                                pw.println(prefix + "No configured app linkages.");
18585                                pw.println();
18586                            }
18587                        }
18588                    }
18589                }
18590            }
18591
18592            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18593                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18594                if (packageName == null && permissionNames == null) {
18595                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18596                        if (iperm == 0) {
18597                            if (dumpState.onTitlePrinted())
18598                                pw.println();
18599                            pw.println("AppOp Permissions:");
18600                        }
18601                        pw.print("  AppOp Permission ");
18602                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18603                        pw.println(":");
18604                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18605                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18606                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18607                        }
18608                    }
18609                }
18610            }
18611
18612            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18613                boolean printedSomething = false;
18614                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18615                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18616                        continue;
18617                    }
18618                    if (!printedSomething) {
18619                        if (dumpState.onTitlePrinted())
18620                            pw.println();
18621                        pw.println("Registered ContentProviders:");
18622                        printedSomething = true;
18623                    }
18624                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18625                    pw.print("    "); pw.println(p.toString());
18626                }
18627                printedSomething = false;
18628                for (Map.Entry<String, PackageParser.Provider> entry :
18629                        mProvidersByAuthority.entrySet()) {
18630                    PackageParser.Provider p = entry.getValue();
18631                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18632                        continue;
18633                    }
18634                    if (!printedSomething) {
18635                        if (dumpState.onTitlePrinted())
18636                            pw.println();
18637                        pw.println("ContentProvider Authorities:");
18638                        printedSomething = true;
18639                    }
18640                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18641                    pw.print("    "); pw.println(p.toString());
18642                    if (p.info != null && p.info.applicationInfo != null) {
18643                        final String appInfo = p.info.applicationInfo.toString();
18644                        pw.print("      applicationInfo="); pw.println(appInfo);
18645                    }
18646                }
18647            }
18648
18649            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18650                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18651            }
18652
18653            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18654                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18655            }
18656
18657            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18658                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18659            }
18660
18661            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18662                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18663            }
18664
18665            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18666                // XXX should handle packageName != null by dumping only install data that
18667                // the given package is involved with.
18668                if (dumpState.onTitlePrinted()) pw.println();
18669                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18670            }
18671
18672            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18673                // XXX should handle packageName != null by dumping only install data that
18674                // the given package is involved with.
18675                if (dumpState.onTitlePrinted()) pw.println();
18676
18677                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18678                ipw.println();
18679                ipw.println("Frozen packages:");
18680                ipw.increaseIndent();
18681                if (mFrozenPackages.size() == 0) {
18682                    ipw.println("(none)");
18683                } else {
18684                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18685                        ipw.println(mFrozenPackages.valueAt(i));
18686                    }
18687                }
18688                ipw.decreaseIndent();
18689            }
18690
18691            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18692                if (dumpState.onTitlePrinted()) pw.println();
18693                dumpDexoptStateLPr(pw, packageName);
18694            }
18695
18696            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18697                if (dumpState.onTitlePrinted()) pw.println();
18698                mSettings.dumpReadMessagesLPr(pw, dumpState);
18699
18700                pw.println();
18701                pw.println("Package warning messages:");
18702                BufferedReader in = null;
18703                String line = null;
18704                try {
18705                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18706                    while ((line = in.readLine()) != null) {
18707                        if (line.contains("ignored: updated version")) continue;
18708                        pw.println(line);
18709                    }
18710                } catch (IOException ignored) {
18711                } finally {
18712                    IoUtils.closeQuietly(in);
18713                }
18714            }
18715
18716            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18717                BufferedReader in = null;
18718                String line = null;
18719                try {
18720                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18721                    while ((line = in.readLine()) != null) {
18722                        if (line.contains("ignored: updated version")) continue;
18723                        pw.print("msg,");
18724                        pw.println(line);
18725                    }
18726                } catch (IOException ignored) {
18727                } finally {
18728                    IoUtils.closeQuietly(in);
18729                }
18730            }
18731        }
18732    }
18733
18734    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18735        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18736        ipw.println();
18737        ipw.println("Dexopt state:");
18738        ipw.increaseIndent();
18739        Collection<PackageParser.Package> packages = null;
18740        if (packageName != null) {
18741            PackageParser.Package targetPackage = mPackages.get(packageName);
18742            if (targetPackage != null) {
18743                packages = Collections.singletonList(targetPackage);
18744            } else {
18745                ipw.println("Unable to find package: " + packageName);
18746                return;
18747            }
18748        } else {
18749            packages = mPackages.values();
18750        }
18751
18752        for (PackageParser.Package pkg : packages) {
18753            ipw.println("[" + pkg.packageName + "]");
18754            ipw.increaseIndent();
18755            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18756            ipw.decreaseIndent();
18757        }
18758    }
18759
18760    private String dumpDomainString(String packageName) {
18761        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18762                .getList();
18763        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18764
18765        ArraySet<String> result = new ArraySet<>();
18766        if (iviList.size() > 0) {
18767            for (IntentFilterVerificationInfo ivi : iviList) {
18768                for (String host : ivi.getDomains()) {
18769                    result.add(host);
18770                }
18771            }
18772        }
18773        if (filters != null && filters.size() > 0) {
18774            for (IntentFilter filter : filters) {
18775                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18776                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18777                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18778                    result.addAll(filter.getHostsList());
18779                }
18780            }
18781        }
18782
18783        StringBuilder sb = new StringBuilder(result.size() * 16);
18784        for (String domain : result) {
18785            if (sb.length() > 0) sb.append(" ");
18786            sb.append(domain);
18787        }
18788        return sb.toString();
18789    }
18790
18791    // ------- apps on sdcard specific code -------
18792    static final boolean DEBUG_SD_INSTALL = false;
18793
18794    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18795
18796    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18797
18798    private boolean mMediaMounted = false;
18799
18800    static String getEncryptKey() {
18801        try {
18802            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18803                    SD_ENCRYPTION_KEYSTORE_NAME);
18804            if (sdEncKey == null) {
18805                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18806                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18807                if (sdEncKey == null) {
18808                    Slog.e(TAG, "Failed to create encryption keys");
18809                    return null;
18810                }
18811            }
18812            return sdEncKey;
18813        } catch (NoSuchAlgorithmException nsae) {
18814            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18815            return null;
18816        } catch (IOException ioe) {
18817            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18818            return null;
18819        }
18820    }
18821
18822    /*
18823     * Update media status on PackageManager.
18824     */
18825    @Override
18826    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18827        int callingUid = Binder.getCallingUid();
18828        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18829            throw new SecurityException("Media status can only be updated by the system");
18830        }
18831        // reader; this apparently protects mMediaMounted, but should probably
18832        // be a different lock in that case.
18833        synchronized (mPackages) {
18834            Log.i(TAG, "Updating external media status from "
18835                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18836                    + (mediaStatus ? "mounted" : "unmounted"));
18837            if (DEBUG_SD_INSTALL)
18838                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18839                        + ", mMediaMounted=" + mMediaMounted);
18840            if (mediaStatus == mMediaMounted) {
18841                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18842                        : 0, -1);
18843                mHandler.sendMessage(msg);
18844                return;
18845            }
18846            mMediaMounted = mediaStatus;
18847        }
18848        // Queue up an async operation since the package installation may take a
18849        // little while.
18850        mHandler.post(new Runnable() {
18851            public void run() {
18852                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18853            }
18854        });
18855    }
18856
18857    /**
18858     * Called by MountService when the initial ASECs to scan are available.
18859     * Should block until all the ASEC containers are finished being scanned.
18860     */
18861    public void scanAvailableAsecs() {
18862        updateExternalMediaStatusInner(true, false, false);
18863    }
18864
18865    /*
18866     * Collect information of applications on external media, map them against
18867     * existing containers and update information based on current mount status.
18868     * Please note that we always have to report status if reportStatus has been
18869     * set to true especially when unloading packages.
18870     */
18871    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18872            boolean externalStorage) {
18873        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18874        int[] uidArr = EmptyArray.INT;
18875
18876        final String[] list = PackageHelper.getSecureContainerList();
18877        if (ArrayUtils.isEmpty(list)) {
18878            Log.i(TAG, "No secure containers found");
18879        } else {
18880            // Process list of secure containers and categorize them
18881            // as active or stale based on their package internal state.
18882
18883            // reader
18884            synchronized (mPackages) {
18885                for (String cid : list) {
18886                    // Leave stages untouched for now; installer service owns them
18887                    if (PackageInstallerService.isStageName(cid)) continue;
18888
18889                    if (DEBUG_SD_INSTALL)
18890                        Log.i(TAG, "Processing container " + cid);
18891                    String pkgName = getAsecPackageName(cid);
18892                    if (pkgName == null) {
18893                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18894                        continue;
18895                    }
18896                    if (DEBUG_SD_INSTALL)
18897                        Log.i(TAG, "Looking for pkg : " + pkgName);
18898
18899                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18900                    if (ps == null) {
18901                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18902                        continue;
18903                    }
18904
18905                    /*
18906                     * Skip packages that are not external if we're unmounting
18907                     * external storage.
18908                     */
18909                    if (externalStorage && !isMounted && !isExternal(ps)) {
18910                        continue;
18911                    }
18912
18913                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18914                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18915                    // The package status is changed only if the code path
18916                    // matches between settings and the container id.
18917                    if (ps.codePathString != null
18918                            && ps.codePathString.startsWith(args.getCodePath())) {
18919                        if (DEBUG_SD_INSTALL) {
18920                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18921                                    + " at code path: " + ps.codePathString);
18922                        }
18923
18924                        // We do have a valid package installed on sdcard
18925                        processCids.put(args, ps.codePathString);
18926                        final int uid = ps.appId;
18927                        if (uid != -1) {
18928                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18929                        }
18930                    } else {
18931                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18932                                + ps.codePathString);
18933                    }
18934                }
18935            }
18936
18937            Arrays.sort(uidArr);
18938        }
18939
18940        // Process packages with valid entries.
18941        if (isMounted) {
18942            if (DEBUG_SD_INSTALL)
18943                Log.i(TAG, "Loading packages");
18944            loadMediaPackages(processCids, uidArr, externalStorage);
18945            startCleaningPackages();
18946            mInstallerService.onSecureContainersAvailable();
18947        } else {
18948            if (DEBUG_SD_INSTALL)
18949                Log.i(TAG, "Unloading packages");
18950            unloadMediaPackages(processCids, uidArr, reportStatus);
18951        }
18952    }
18953
18954    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18955            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18956        final int size = infos.size();
18957        final String[] packageNames = new String[size];
18958        final int[] packageUids = new int[size];
18959        for (int i = 0; i < size; i++) {
18960            final ApplicationInfo info = infos.get(i);
18961            packageNames[i] = info.packageName;
18962            packageUids[i] = info.uid;
18963        }
18964        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18965                finishedReceiver);
18966    }
18967
18968    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18969            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18970        sendResourcesChangedBroadcast(mediaStatus, replacing,
18971                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18972    }
18973
18974    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18975            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18976        int size = pkgList.length;
18977        if (size > 0) {
18978            // Send broadcasts here
18979            Bundle extras = new Bundle();
18980            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18981            if (uidArr != null) {
18982                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18983            }
18984            if (replacing) {
18985                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18986            }
18987            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18988                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18989            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18990        }
18991    }
18992
18993   /*
18994     * Look at potentially valid container ids from processCids If package
18995     * information doesn't match the one on record or package scanning fails,
18996     * the cid is added to list of removeCids. We currently don't delete stale
18997     * containers.
18998     */
18999    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
19000            boolean externalStorage) {
19001        ArrayList<String> pkgList = new ArrayList<String>();
19002        Set<AsecInstallArgs> keys = processCids.keySet();
19003
19004        for (AsecInstallArgs args : keys) {
19005            String codePath = processCids.get(args);
19006            if (DEBUG_SD_INSTALL)
19007                Log.i(TAG, "Loading container : " + args.cid);
19008            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19009            try {
19010                // Make sure there are no container errors first.
19011                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19012                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19013                            + " when installing from sdcard");
19014                    continue;
19015                }
19016                // Check code path here.
19017                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19018                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19019                            + " does not match one in settings " + codePath);
19020                    continue;
19021                }
19022                // Parse package
19023                int parseFlags = mDefParseFlags;
19024                if (args.isExternalAsec()) {
19025                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19026                }
19027                if (args.isFwdLocked()) {
19028                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19029                }
19030
19031                synchronized (mInstallLock) {
19032                    PackageParser.Package pkg = null;
19033                    try {
19034                        // Sadly we don't know the package name yet to freeze it
19035                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19036                                SCAN_IGNORE_FROZEN, 0, null);
19037                    } catch (PackageManagerException e) {
19038                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19039                    }
19040                    // Scan the package
19041                    if (pkg != null) {
19042                        /*
19043                         * TODO why is the lock being held? doPostInstall is
19044                         * called in other places without the lock. This needs
19045                         * to be straightened out.
19046                         */
19047                        // writer
19048                        synchronized (mPackages) {
19049                            retCode = PackageManager.INSTALL_SUCCEEDED;
19050                            pkgList.add(pkg.packageName);
19051                            // Post process args
19052                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19053                                    pkg.applicationInfo.uid);
19054                        }
19055                    } else {
19056                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19057                    }
19058                }
19059
19060            } finally {
19061                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19062                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19063                }
19064            }
19065        }
19066        // writer
19067        synchronized (mPackages) {
19068            // If the platform SDK has changed since the last time we booted,
19069            // we need to re-grant app permission to catch any new ones that
19070            // appear. This is really a hack, and means that apps can in some
19071            // cases get permissions that the user didn't initially explicitly
19072            // allow... it would be nice to have some better way to handle
19073            // this situation.
19074            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19075                    : mSettings.getInternalVersion();
19076            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19077                    : StorageManager.UUID_PRIVATE_INTERNAL;
19078
19079            int updateFlags = UPDATE_PERMISSIONS_ALL;
19080            if (ver.sdkVersion != mSdkVersion) {
19081                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19082                        + mSdkVersion + "; regranting permissions for external");
19083                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19084            }
19085            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19086
19087            // Yay, everything is now upgraded
19088            ver.forceCurrent();
19089
19090            // can downgrade to reader
19091            // Persist settings
19092            mSettings.writeLPr();
19093        }
19094        // Send a broadcast to let everyone know we are done processing
19095        if (pkgList.size() > 0) {
19096            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19097        }
19098    }
19099
19100   /*
19101     * Utility method to unload a list of specified containers
19102     */
19103    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19104        // Just unmount all valid containers.
19105        for (AsecInstallArgs arg : cidArgs) {
19106            synchronized (mInstallLock) {
19107                arg.doPostDeleteLI(false);
19108           }
19109       }
19110   }
19111
19112    /*
19113     * Unload packages mounted on external media. This involves deleting package
19114     * data from internal structures, sending broadcasts about disabled packages,
19115     * gc'ing to free up references, unmounting all secure containers
19116     * corresponding to packages on external media, and posting a
19117     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19118     * that we always have to post this message if status has been requested no
19119     * matter what.
19120     */
19121    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19122            final boolean reportStatus) {
19123        if (DEBUG_SD_INSTALL)
19124            Log.i(TAG, "unloading media packages");
19125        ArrayList<String> pkgList = new ArrayList<String>();
19126        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19127        final Set<AsecInstallArgs> keys = processCids.keySet();
19128        for (AsecInstallArgs args : keys) {
19129            String pkgName = args.getPackageName();
19130            if (DEBUG_SD_INSTALL)
19131                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19132            // Delete package internally
19133            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19134            synchronized (mInstallLock) {
19135                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19136                final boolean res;
19137                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19138                        "unloadMediaPackages")) {
19139                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19140                            null);
19141                }
19142                if (res) {
19143                    pkgList.add(pkgName);
19144                } else {
19145                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19146                    failedList.add(args);
19147                }
19148            }
19149        }
19150
19151        // reader
19152        synchronized (mPackages) {
19153            // We didn't update the settings after removing each package;
19154            // write them now for all packages.
19155            mSettings.writeLPr();
19156        }
19157
19158        // We have to absolutely send UPDATED_MEDIA_STATUS only
19159        // after confirming that all the receivers processed the ordered
19160        // broadcast when packages get disabled, force a gc to clean things up.
19161        // and unload all the containers.
19162        if (pkgList.size() > 0) {
19163            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19164                    new IIntentReceiver.Stub() {
19165                public void performReceive(Intent intent, int resultCode, String data,
19166                        Bundle extras, boolean ordered, boolean sticky,
19167                        int sendingUser) throws RemoteException {
19168                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19169                            reportStatus ? 1 : 0, 1, keys);
19170                    mHandler.sendMessage(msg);
19171                }
19172            });
19173        } else {
19174            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19175                    keys);
19176            mHandler.sendMessage(msg);
19177        }
19178    }
19179
19180    private void loadPrivatePackages(final VolumeInfo vol) {
19181        mHandler.post(new Runnable() {
19182            @Override
19183            public void run() {
19184                loadPrivatePackagesInner(vol);
19185            }
19186        });
19187    }
19188
19189    private void loadPrivatePackagesInner(VolumeInfo vol) {
19190        final String volumeUuid = vol.fsUuid;
19191        if (TextUtils.isEmpty(volumeUuid)) {
19192            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19193            return;
19194        }
19195
19196        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19197        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19198        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19199
19200        final VersionInfo ver;
19201        final List<PackageSetting> packages;
19202        synchronized (mPackages) {
19203            ver = mSettings.findOrCreateVersion(volumeUuid);
19204            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19205        }
19206
19207        for (PackageSetting ps : packages) {
19208            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19209            synchronized (mInstallLock) {
19210                final PackageParser.Package pkg;
19211                try {
19212                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19213                    loaded.add(pkg.applicationInfo);
19214
19215                } catch (PackageManagerException e) {
19216                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19217                }
19218
19219                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19220                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19221                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19222                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19223                }
19224            }
19225        }
19226
19227        // Reconcile app data for all started/unlocked users
19228        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19229        final UserManager um = mContext.getSystemService(UserManager.class);
19230        UserManagerInternal umInternal = getUserManagerInternal();
19231        for (UserInfo user : um.getUsers()) {
19232            final int flags;
19233            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19234                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19235            } else if (umInternal.isUserRunning(user.id)) {
19236                flags = StorageManager.FLAG_STORAGE_DE;
19237            } else {
19238                continue;
19239            }
19240
19241            try {
19242                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19243                synchronized (mInstallLock) {
19244                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19245                }
19246            } catch (IllegalStateException e) {
19247                // Device was probably ejected, and we'll process that event momentarily
19248                Slog.w(TAG, "Failed to prepare storage: " + e);
19249            }
19250        }
19251
19252        synchronized (mPackages) {
19253            int updateFlags = UPDATE_PERMISSIONS_ALL;
19254            if (ver.sdkVersion != mSdkVersion) {
19255                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19256                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19257                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19258            }
19259            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19260
19261            // Yay, everything is now upgraded
19262            ver.forceCurrent();
19263
19264            mSettings.writeLPr();
19265        }
19266
19267        for (PackageFreezer freezer : freezers) {
19268            freezer.close();
19269        }
19270
19271        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19272        sendResourcesChangedBroadcast(true, false, loaded, null);
19273    }
19274
19275    private void unloadPrivatePackages(final VolumeInfo vol) {
19276        mHandler.post(new Runnable() {
19277            @Override
19278            public void run() {
19279                unloadPrivatePackagesInner(vol);
19280            }
19281        });
19282    }
19283
19284    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19285        final String volumeUuid = vol.fsUuid;
19286        if (TextUtils.isEmpty(volumeUuid)) {
19287            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19288            return;
19289        }
19290
19291        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19292        synchronized (mInstallLock) {
19293        synchronized (mPackages) {
19294            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19295            for (PackageSetting ps : packages) {
19296                if (ps.pkg == null) continue;
19297
19298                final ApplicationInfo info = ps.pkg.applicationInfo;
19299                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19300                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19301
19302                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19303                        "unloadPrivatePackagesInner")) {
19304                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19305                            false, null)) {
19306                        unloaded.add(info);
19307                    } else {
19308                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19309                    }
19310                }
19311
19312                // Try very hard to release any references to this package
19313                // so we don't risk the system server being killed due to
19314                // open FDs
19315                AttributeCache.instance().removePackage(ps.name);
19316            }
19317
19318            mSettings.writeLPr();
19319        }
19320        }
19321
19322        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19323        sendResourcesChangedBroadcast(false, false, unloaded, null);
19324
19325        // Try very hard to release any references to this path so we don't risk
19326        // the system server being killed due to open FDs
19327        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19328
19329        for (int i = 0; i < 3; i++) {
19330            System.gc();
19331            System.runFinalization();
19332        }
19333    }
19334
19335    /**
19336     * Prepare storage areas for given user on all mounted devices.
19337     */
19338    void prepareUserData(int userId, int userSerial, int flags) {
19339        synchronized (mInstallLock) {
19340            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19341            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19342                final String volumeUuid = vol.getFsUuid();
19343                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19344            }
19345        }
19346    }
19347
19348    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19349            boolean allowRecover) {
19350        // Prepare storage and verify that serial numbers are consistent; if
19351        // there's a mismatch we need to destroy to avoid leaking data
19352        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19353        try {
19354            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19355
19356            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19357                UserManagerService.enforceSerialNumber(
19358                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19359            }
19360            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19361                UserManagerService.enforceSerialNumber(
19362                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19363            }
19364
19365            synchronized (mInstallLock) {
19366                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19367            }
19368        } catch (Exception e) {
19369            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19370                    + " because we failed to prepare: " + e);
19371            destroyUserDataLI(volumeUuid, userId,
19372                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19373
19374            if (allowRecover) {
19375                // Try one last time; if we fail again we're really in trouble
19376                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19377            }
19378        }
19379    }
19380
19381    /**
19382     * Destroy storage areas for given user on all mounted devices.
19383     */
19384    void destroyUserData(int userId, int flags) {
19385        synchronized (mInstallLock) {
19386            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19387            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19388                final String volumeUuid = vol.getFsUuid();
19389                destroyUserDataLI(volumeUuid, userId, flags);
19390            }
19391        }
19392    }
19393
19394    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19395        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19396        try {
19397            // Clean up app data, profile data, and media data
19398            mInstaller.destroyUserData(volumeUuid, userId, flags);
19399
19400            // Clean up system data
19401            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19402                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19403                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19404                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19405                }
19406                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19407                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19408                }
19409            }
19410
19411            // Data with special labels is now gone, so finish the job
19412            storage.destroyUserStorage(volumeUuid, userId, flags);
19413
19414        } catch (Exception e) {
19415            logCriticalInfo(Log.WARN,
19416                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19417        }
19418    }
19419
19420    /**
19421     * Examine all users present on given mounted volume, and destroy data
19422     * belonging to users that are no longer valid, or whose user ID has been
19423     * recycled.
19424     */
19425    private void reconcileUsers(String volumeUuid) {
19426        final List<File> files = new ArrayList<>();
19427        Collections.addAll(files, FileUtils
19428                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19429        Collections.addAll(files, FileUtils
19430                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19431        for (File file : files) {
19432            if (!file.isDirectory()) continue;
19433
19434            final int userId;
19435            final UserInfo info;
19436            try {
19437                userId = Integer.parseInt(file.getName());
19438                info = sUserManager.getUserInfo(userId);
19439            } catch (NumberFormatException e) {
19440                Slog.w(TAG, "Invalid user directory " + file);
19441                continue;
19442            }
19443
19444            boolean destroyUser = false;
19445            if (info == null) {
19446                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19447                        + " because no matching user was found");
19448                destroyUser = true;
19449            } else if (!mOnlyCore) {
19450                try {
19451                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19452                } catch (IOException e) {
19453                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19454                            + " because we failed to enforce serial number: " + e);
19455                    destroyUser = true;
19456                }
19457            }
19458
19459            if (destroyUser) {
19460                synchronized (mInstallLock) {
19461                    destroyUserDataLI(volumeUuid, userId,
19462                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19463                }
19464            }
19465        }
19466    }
19467
19468    private void assertPackageKnown(String volumeUuid, String packageName)
19469            throws PackageManagerException {
19470        synchronized (mPackages) {
19471            final PackageSetting ps = mSettings.mPackages.get(packageName);
19472            if (ps == null) {
19473                throw new PackageManagerException("Package " + packageName + " is unknown");
19474            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19475                throw new PackageManagerException(
19476                        "Package " + packageName + " found on unknown volume " + volumeUuid
19477                                + "; expected volume " + ps.volumeUuid);
19478            }
19479        }
19480    }
19481
19482    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19483            throws PackageManagerException {
19484        synchronized (mPackages) {
19485            final PackageSetting ps = mSettings.mPackages.get(packageName);
19486            if (ps == null) {
19487                throw new PackageManagerException("Package " + packageName + " is unknown");
19488            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19489                throw new PackageManagerException(
19490                        "Package " + packageName + " found on unknown volume " + volumeUuid
19491                                + "; expected volume " + ps.volumeUuid);
19492            } else if (!ps.getInstalled(userId)) {
19493                throw new PackageManagerException(
19494                        "Package " + packageName + " not installed for user " + userId);
19495            }
19496        }
19497    }
19498
19499    /**
19500     * Examine all apps present on given mounted volume, and destroy apps that
19501     * aren't expected, either due to uninstallation or reinstallation on
19502     * another volume.
19503     */
19504    private void reconcileApps(String volumeUuid) {
19505        final File[] files = FileUtils
19506                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19507        for (File file : files) {
19508            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19509                    && !PackageInstallerService.isStageName(file.getName());
19510            if (!isPackage) {
19511                // Ignore entries which are not packages
19512                continue;
19513            }
19514
19515            try {
19516                final PackageLite pkg = PackageParser.parsePackageLite(file,
19517                        PackageParser.PARSE_MUST_BE_APK);
19518                assertPackageKnown(volumeUuid, pkg.packageName);
19519
19520            } catch (PackageParserException | PackageManagerException e) {
19521                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19522                synchronized (mInstallLock) {
19523                    removeCodePathLI(file);
19524                }
19525            }
19526        }
19527    }
19528
19529    /**
19530     * Reconcile all app data for the given user.
19531     * <p>
19532     * Verifies that directories exist and that ownership and labeling is
19533     * correct for all installed apps on all mounted volumes.
19534     */
19535    void reconcileAppsData(int userId, int flags) {
19536        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19537        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19538            final String volumeUuid = vol.getFsUuid();
19539            synchronized (mInstallLock) {
19540                reconcileAppsDataLI(volumeUuid, userId, flags);
19541            }
19542        }
19543    }
19544
19545    /**
19546     * Reconcile all app data on given mounted volume.
19547     * <p>
19548     * Destroys app data that isn't expected, either due to uninstallation or
19549     * reinstallation on another volume.
19550     * <p>
19551     * Verifies that directories exist and that ownership and labeling is
19552     * correct for all installed apps.
19553     */
19554    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19555        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19556                + Integer.toHexString(flags));
19557
19558        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19559        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19560
19561        boolean restoreconNeeded = false;
19562
19563        // First look for stale data that doesn't belong, and check if things
19564        // have changed since we did our last restorecon
19565        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19566            if (StorageManager.isFileEncryptedNativeOrEmulated()
19567                    && !StorageManager.isUserKeyUnlocked(userId)) {
19568                throw new RuntimeException(
19569                        "Yikes, someone asked us to reconcile CE storage while " + userId
19570                                + " was still locked; this would have caused massive data loss!");
19571            }
19572
19573            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19574
19575            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19576            for (File file : files) {
19577                final String packageName = file.getName();
19578                try {
19579                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19580                } catch (PackageManagerException e) {
19581                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19582                    try {
19583                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19584                                StorageManager.FLAG_STORAGE_CE, 0);
19585                    } catch (InstallerException e2) {
19586                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19587                    }
19588                }
19589            }
19590        }
19591        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19592            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19593
19594            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19595            for (File file : files) {
19596                final String packageName = file.getName();
19597                try {
19598                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19599                } catch (PackageManagerException e) {
19600                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19601                    try {
19602                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19603                                StorageManager.FLAG_STORAGE_DE, 0);
19604                    } catch (InstallerException e2) {
19605                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19606                    }
19607                }
19608            }
19609        }
19610
19611        // Ensure that data directories are ready to roll for all packages
19612        // installed for this volume and user
19613        final List<PackageSetting> packages;
19614        synchronized (mPackages) {
19615            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19616        }
19617        int preparedCount = 0;
19618        for (PackageSetting ps : packages) {
19619            final String packageName = ps.name;
19620            if (ps.pkg == null) {
19621                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19622                // TODO: might be due to legacy ASEC apps; we should circle back
19623                // and reconcile again once they're scanned
19624                continue;
19625            }
19626
19627            if (ps.getInstalled(userId)) {
19628                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19629
19630                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19631                    // We may have just shuffled around app data directories, so
19632                    // prepare them one more time
19633                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19634                }
19635
19636                preparedCount++;
19637            }
19638        }
19639
19640        if (restoreconNeeded) {
19641            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19642                SELinuxMMAC.setRestoreconDone(ceDir);
19643            }
19644            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19645                SELinuxMMAC.setRestoreconDone(deDir);
19646            }
19647        }
19648
19649        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19650                + " packages; restoreconNeeded was " + restoreconNeeded);
19651    }
19652
19653    /**
19654     * Prepare app data for the given app just after it was installed or
19655     * upgraded. This method carefully only touches users that it's installed
19656     * for, and it forces a restorecon to handle any seinfo changes.
19657     * <p>
19658     * Verifies that directories exist and that ownership and labeling is
19659     * correct for all installed apps. If there is an ownership mismatch, it
19660     * will try recovering system apps by wiping data; third-party app data is
19661     * left intact.
19662     * <p>
19663     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19664     */
19665    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19666        final PackageSetting ps;
19667        synchronized (mPackages) {
19668            ps = mSettings.mPackages.get(pkg.packageName);
19669            mSettings.writeKernelMappingLPr(ps);
19670        }
19671
19672        final UserManager um = mContext.getSystemService(UserManager.class);
19673        UserManagerInternal umInternal = getUserManagerInternal();
19674        for (UserInfo user : um.getUsers()) {
19675            final int flags;
19676            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19677                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19678            } else if (umInternal.isUserRunning(user.id)) {
19679                flags = StorageManager.FLAG_STORAGE_DE;
19680            } else {
19681                continue;
19682            }
19683
19684            if (ps.getInstalled(user.id)) {
19685                // Whenever an app changes, force a restorecon of its data
19686                // TODO: when user data is locked, mark that we're still dirty
19687                prepareAppDataLIF(pkg, user.id, flags, true);
19688            }
19689        }
19690    }
19691
19692    /**
19693     * Prepare app data for the given app.
19694     * <p>
19695     * Verifies that directories exist and that ownership and labeling is
19696     * correct for all installed apps. If there is an ownership mismatch, this
19697     * will try recovering system apps by wiping data; third-party app data is
19698     * left intact.
19699     */
19700    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19701            boolean restoreconNeeded) {
19702        if (pkg == null) {
19703            Slog.wtf(TAG, "Package was null!", new Throwable());
19704            return;
19705        }
19706        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19707        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19708        for (int i = 0; i < childCount; i++) {
19709            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19710        }
19711    }
19712
19713    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19714            boolean restoreconNeeded) {
19715        if (DEBUG_APP_DATA) {
19716            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19717                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19718        }
19719
19720        final String volumeUuid = pkg.volumeUuid;
19721        final String packageName = pkg.packageName;
19722        final ApplicationInfo app = pkg.applicationInfo;
19723        final int appId = UserHandle.getAppId(app.uid);
19724
19725        Preconditions.checkNotNull(app.seinfo);
19726
19727        try {
19728            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19729                    appId, app.seinfo, app.targetSdkVersion);
19730        } catch (InstallerException e) {
19731            if (app.isSystemApp()) {
19732                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19733                        + ", but trying to recover: " + e);
19734                destroyAppDataLeafLIF(pkg, userId, flags);
19735                try {
19736                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19737                            appId, app.seinfo, app.targetSdkVersion);
19738                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19739                } catch (InstallerException e2) {
19740                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19741                }
19742            } else {
19743                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19744            }
19745        }
19746
19747        if (restoreconNeeded) {
19748            try {
19749                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19750                        app.seinfo);
19751            } catch (InstallerException e) {
19752                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19753            }
19754        }
19755
19756        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19757            try {
19758                // CE storage is unlocked right now, so read out the inode and
19759                // remember for use later when it's locked
19760                // TODO: mark this structure as dirty so we persist it!
19761                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19762                        StorageManager.FLAG_STORAGE_CE);
19763                synchronized (mPackages) {
19764                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19765                    if (ps != null) {
19766                        ps.setCeDataInode(ceDataInode, userId);
19767                    }
19768                }
19769            } catch (InstallerException e) {
19770                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19771            }
19772        }
19773
19774        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19775    }
19776
19777    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19778        if (pkg == null) {
19779            Slog.wtf(TAG, "Package was null!", new Throwable());
19780            return;
19781        }
19782        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19783        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19784        for (int i = 0; i < childCount; i++) {
19785            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19786        }
19787    }
19788
19789    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19790        final String volumeUuid = pkg.volumeUuid;
19791        final String packageName = pkg.packageName;
19792        final ApplicationInfo app = pkg.applicationInfo;
19793
19794        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19795            // Create a native library symlink only if we have native libraries
19796            // and if the native libraries are 32 bit libraries. We do not provide
19797            // this symlink for 64 bit libraries.
19798            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19799                final String nativeLibPath = app.nativeLibraryDir;
19800                try {
19801                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19802                            nativeLibPath, userId);
19803                } catch (InstallerException e) {
19804                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19805                }
19806            }
19807        }
19808    }
19809
19810    /**
19811     * For system apps on non-FBE devices, this method migrates any existing
19812     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19813     * requested by the app.
19814     */
19815    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19816        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19817                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19818            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19819                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19820            try {
19821                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19822                        storageTarget);
19823            } catch (InstallerException e) {
19824                logCriticalInfo(Log.WARN,
19825                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19826            }
19827            return true;
19828        } else {
19829            return false;
19830        }
19831    }
19832
19833    public PackageFreezer freezePackage(String packageName, String killReason) {
19834        return new PackageFreezer(packageName, killReason);
19835    }
19836
19837    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19838            String killReason) {
19839        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19840            return new PackageFreezer();
19841        } else {
19842            return freezePackage(packageName, killReason);
19843        }
19844    }
19845
19846    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19847            String killReason) {
19848        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19849            return new PackageFreezer();
19850        } else {
19851            return freezePackage(packageName, killReason);
19852        }
19853    }
19854
19855    /**
19856     * Class that freezes and kills the given package upon creation, and
19857     * unfreezes it upon closing. This is typically used when doing surgery on
19858     * app code/data to prevent the app from running while you're working.
19859     */
19860    private class PackageFreezer implements AutoCloseable {
19861        private final String mPackageName;
19862        private final PackageFreezer[] mChildren;
19863
19864        private final boolean mWeFroze;
19865
19866        private final AtomicBoolean mClosed = new AtomicBoolean();
19867        private final CloseGuard mCloseGuard = CloseGuard.get();
19868
19869        /**
19870         * Create and return a stub freezer that doesn't actually do anything,
19871         * typically used when someone requested
19872         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19873         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19874         */
19875        public PackageFreezer() {
19876            mPackageName = null;
19877            mChildren = null;
19878            mWeFroze = false;
19879            mCloseGuard.open("close");
19880        }
19881
19882        public PackageFreezer(String packageName, String killReason) {
19883            synchronized (mPackages) {
19884                mPackageName = packageName;
19885                mWeFroze = mFrozenPackages.add(mPackageName);
19886
19887                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19888                if (ps != null) {
19889                    killApplication(ps.name, ps.appId, killReason);
19890                }
19891
19892                final PackageParser.Package p = mPackages.get(packageName);
19893                if (p != null && p.childPackages != null) {
19894                    final int N = p.childPackages.size();
19895                    mChildren = new PackageFreezer[N];
19896                    for (int i = 0; i < N; i++) {
19897                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19898                                killReason);
19899                    }
19900                } else {
19901                    mChildren = null;
19902                }
19903            }
19904            mCloseGuard.open("close");
19905        }
19906
19907        @Override
19908        protected void finalize() throws Throwable {
19909            try {
19910                mCloseGuard.warnIfOpen();
19911                close();
19912            } finally {
19913                super.finalize();
19914            }
19915        }
19916
19917        @Override
19918        public void close() {
19919            mCloseGuard.close();
19920            if (mClosed.compareAndSet(false, true)) {
19921                synchronized (mPackages) {
19922                    if (mWeFroze) {
19923                        mFrozenPackages.remove(mPackageName);
19924                    }
19925
19926                    if (mChildren != null) {
19927                        for (PackageFreezer freezer : mChildren) {
19928                            freezer.close();
19929                        }
19930                    }
19931                }
19932            }
19933        }
19934    }
19935
19936    /**
19937     * Verify that given package is currently frozen.
19938     */
19939    private void checkPackageFrozen(String packageName) {
19940        synchronized (mPackages) {
19941            if (!mFrozenPackages.contains(packageName)) {
19942                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19943            }
19944        }
19945    }
19946
19947    @Override
19948    public int movePackage(final String packageName, final String volumeUuid) {
19949        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19950
19951        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19952        final int moveId = mNextMoveId.getAndIncrement();
19953        mHandler.post(new Runnable() {
19954            @Override
19955            public void run() {
19956                try {
19957                    movePackageInternal(packageName, volumeUuid, moveId, user);
19958                } catch (PackageManagerException e) {
19959                    Slog.w(TAG, "Failed to move " + packageName, e);
19960                    mMoveCallbacks.notifyStatusChanged(moveId,
19961                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19962                }
19963            }
19964        });
19965        return moveId;
19966    }
19967
19968    private void movePackageInternal(final String packageName, final String volumeUuid,
19969            final int moveId, UserHandle user) throws PackageManagerException {
19970        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19971        final PackageManager pm = mContext.getPackageManager();
19972
19973        final boolean currentAsec;
19974        final String currentVolumeUuid;
19975        final File codeFile;
19976        final String installerPackageName;
19977        final String packageAbiOverride;
19978        final int appId;
19979        final String seinfo;
19980        final String label;
19981        final int targetSdkVersion;
19982        final PackageFreezer freezer;
19983        final int[] installedUserIds;
19984
19985        // reader
19986        synchronized (mPackages) {
19987            final PackageParser.Package pkg = mPackages.get(packageName);
19988            final PackageSetting ps = mSettings.mPackages.get(packageName);
19989            if (pkg == null || ps == null) {
19990                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
19991            }
19992
19993            if (pkg.applicationInfo.isSystemApp()) {
19994                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
19995                        "Cannot move system application");
19996            }
19997
19998            if (pkg.applicationInfo.isExternalAsec()) {
19999                currentAsec = true;
20000                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20001            } else if (pkg.applicationInfo.isForwardLocked()) {
20002                currentAsec = true;
20003                currentVolumeUuid = "forward_locked";
20004            } else {
20005                currentAsec = false;
20006                currentVolumeUuid = ps.volumeUuid;
20007
20008                final File probe = new File(pkg.codePath);
20009                final File probeOat = new File(probe, "oat");
20010                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20011                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20012                            "Move only supported for modern cluster style installs");
20013                }
20014            }
20015
20016            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20017                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20018                        "Package already moved to " + volumeUuid);
20019            }
20020            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20021                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20022                        "Device admin cannot be moved");
20023            }
20024
20025            if (mFrozenPackages.contains(packageName)) {
20026                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20027                        "Failed to move already frozen package");
20028            }
20029
20030            codeFile = new File(pkg.codePath);
20031            installerPackageName = ps.installerPackageName;
20032            packageAbiOverride = ps.cpuAbiOverrideString;
20033            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20034            seinfo = pkg.applicationInfo.seinfo;
20035            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20036            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20037            freezer = new PackageFreezer(packageName, "movePackageInternal");
20038            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20039        }
20040
20041        final Bundle extras = new Bundle();
20042        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20043        extras.putString(Intent.EXTRA_TITLE, label);
20044        mMoveCallbacks.notifyCreated(moveId, extras);
20045
20046        int installFlags;
20047        final boolean moveCompleteApp;
20048        final File measurePath;
20049
20050        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20051            installFlags = INSTALL_INTERNAL;
20052            moveCompleteApp = !currentAsec;
20053            measurePath = Environment.getDataAppDirectory(volumeUuid);
20054        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20055            installFlags = INSTALL_EXTERNAL;
20056            moveCompleteApp = false;
20057            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20058        } else {
20059            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20060            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20061                    || !volume.isMountedWritable()) {
20062                freezer.close();
20063                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20064                        "Move location not mounted private volume");
20065            }
20066
20067            Preconditions.checkState(!currentAsec);
20068
20069            installFlags = INSTALL_INTERNAL;
20070            moveCompleteApp = true;
20071            measurePath = Environment.getDataAppDirectory(volumeUuid);
20072        }
20073
20074        final PackageStats stats = new PackageStats(null, -1);
20075        synchronized (mInstaller) {
20076            for (int userId : installedUserIds) {
20077                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20078                    freezer.close();
20079                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20080                            "Failed to measure package size");
20081                }
20082            }
20083        }
20084
20085        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20086                + stats.dataSize);
20087
20088        final long startFreeBytes = measurePath.getFreeSpace();
20089        final long sizeBytes;
20090        if (moveCompleteApp) {
20091            sizeBytes = stats.codeSize + stats.dataSize;
20092        } else {
20093            sizeBytes = stats.codeSize;
20094        }
20095
20096        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20097            freezer.close();
20098            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20099                    "Not enough free space to move");
20100        }
20101
20102        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20103
20104        final CountDownLatch installedLatch = new CountDownLatch(1);
20105        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20106            @Override
20107            public void onUserActionRequired(Intent intent) throws RemoteException {
20108                throw new IllegalStateException();
20109            }
20110
20111            @Override
20112            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20113                    Bundle extras) throws RemoteException {
20114                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20115                        + PackageManager.installStatusToString(returnCode, msg));
20116
20117                installedLatch.countDown();
20118                freezer.close();
20119
20120                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20121                switch (status) {
20122                    case PackageInstaller.STATUS_SUCCESS:
20123                        mMoveCallbacks.notifyStatusChanged(moveId,
20124                                PackageManager.MOVE_SUCCEEDED);
20125                        break;
20126                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20127                        mMoveCallbacks.notifyStatusChanged(moveId,
20128                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20129                        break;
20130                    default:
20131                        mMoveCallbacks.notifyStatusChanged(moveId,
20132                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20133                        break;
20134                }
20135            }
20136        };
20137
20138        final MoveInfo move;
20139        if (moveCompleteApp) {
20140            // Kick off a thread to report progress estimates
20141            new Thread() {
20142                @Override
20143                public void run() {
20144                    while (true) {
20145                        try {
20146                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20147                                break;
20148                            }
20149                        } catch (InterruptedException ignored) {
20150                        }
20151
20152                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20153                        final int progress = 10 + (int) MathUtils.constrain(
20154                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20155                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20156                    }
20157                }
20158            }.start();
20159
20160            final String dataAppName = codeFile.getName();
20161            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20162                    dataAppName, appId, seinfo, targetSdkVersion);
20163        } else {
20164            move = null;
20165        }
20166
20167        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20168
20169        final Message msg = mHandler.obtainMessage(INIT_COPY);
20170        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20171        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20172                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20173                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20174        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20175        msg.obj = params;
20176
20177        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20178                System.identityHashCode(msg.obj));
20179        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20180                System.identityHashCode(msg.obj));
20181
20182        mHandler.sendMessage(msg);
20183    }
20184
20185    @Override
20186    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20187        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20188
20189        final int realMoveId = mNextMoveId.getAndIncrement();
20190        final Bundle extras = new Bundle();
20191        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20192        mMoveCallbacks.notifyCreated(realMoveId, extras);
20193
20194        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20195            @Override
20196            public void onCreated(int moveId, Bundle extras) {
20197                // Ignored
20198            }
20199
20200            @Override
20201            public void onStatusChanged(int moveId, int status, long estMillis) {
20202                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20203            }
20204        };
20205
20206        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20207        storage.setPrimaryStorageUuid(volumeUuid, callback);
20208        return realMoveId;
20209    }
20210
20211    @Override
20212    public int getMoveStatus(int moveId) {
20213        mContext.enforceCallingOrSelfPermission(
20214                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20215        return mMoveCallbacks.mLastStatus.get(moveId);
20216    }
20217
20218    @Override
20219    public void registerMoveCallback(IPackageMoveObserver callback) {
20220        mContext.enforceCallingOrSelfPermission(
20221                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20222        mMoveCallbacks.register(callback);
20223    }
20224
20225    @Override
20226    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20227        mContext.enforceCallingOrSelfPermission(
20228                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20229        mMoveCallbacks.unregister(callback);
20230    }
20231
20232    @Override
20233    public boolean setInstallLocation(int loc) {
20234        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20235                null);
20236        if (getInstallLocation() == loc) {
20237            return true;
20238        }
20239        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20240                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20241            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20242                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20243            return true;
20244        }
20245        return false;
20246   }
20247
20248    @Override
20249    public int getInstallLocation() {
20250        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20251                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20252                PackageHelper.APP_INSTALL_AUTO);
20253    }
20254
20255    /** Called by UserManagerService */
20256    void cleanUpUser(UserManagerService userManager, int userHandle) {
20257        synchronized (mPackages) {
20258            mDirtyUsers.remove(userHandle);
20259            mUserNeedsBadging.delete(userHandle);
20260            mSettings.removeUserLPw(userHandle);
20261            mPendingBroadcasts.remove(userHandle);
20262            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20263            removeUnusedPackagesLPw(userManager, userHandle);
20264        }
20265    }
20266
20267    /**
20268     * We're removing userHandle and would like to remove any downloaded packages
20269     * that are no longer in use by any other user.
20270     * @param userHandle the user being removed
20271     */
20272    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20273        final boolean DEBUG_CLEAN_APKS = false;
20274        int [] users = userManager.getUserIds();
20275        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20276        while (psit.hasNext()) {
20277            PackageSetting ps = psit.next();
20278            if (ps.pkg == null) {
20279                continue;
20280            }
20281            final String packageName = ps.pkg.packageName;
20282            // Skip over if system app
20283            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20284                continue;
20285            }
20286            if (DEBUG_CLEAN_APKS) {
20287                Slog.i(TAG, "Checking package " + packageName);
20288            }
20289            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20290            if (keep) {
20291                if (DEBUG_CLEAN_APKS) {
20292                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20293                }
20294            } else {
20295                for (int i = 0; i < users.length; i++) {
20296                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20297                        keep = true;
20298                        if (DEBUG_CLEAN_APKS) {
20299                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20300                                    + users[i]);
20301                        }
20302                        break;
20303                    }
20304                }
20305            }
20306            if (!keep) {
20307                if (DEBUG_CLEAN_APKS) {
20308                    Slog.i(TAG, "  Removing package " + packageName);
20309                }
20310                mHandler.post(new Runnable() {
20311                    public void run() {
20312                        deletePackageX(packageName, userHandle, 0);
20313                    } //end run
20314                });
20315            }
20316        }
20317    }
20318
20319    /** Called by UserManagerService */
20320    void createNewUser(int userId) {
20321        synchronized (mInstallLock) {
20322            mSettings.createNewUserLI(this, mInstaller, userId);
20323        }
20324        synchronized (mPackages) {
20325            scheduleWritePackageRestrictionsLocked(userId);
20326            scheduleWritePackageListLocked(userId);
20327            applyFactoryDefaultBrowserLPw(userId);
20328            primeDomainVerificationsLPw(userId);
20329        }
20330    }
20331
20332    void onBeforeUserStartUninitialized(final int userId) {
20333        synchronized (mPackages) {
20334            if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20335                return;
20336            }
20337        }
20338        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20339        // If permission review for legacy apps is required, we represent
20340        // dagerous permissions for such apps as always granted runtime
20341        // permissions to keep per user flag state whether review is needed.
20342        // Hence, if a new user is added we have to propagate dangerous
20343        // permission grants for these legacy apps.
20344        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20345            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20346                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20347        }
20348    }
20349
20350    @Override
20351    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20352        mContext.enforceCallingOrSelfPermission(
20353                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20354                "Only package verification agents can read the verifier device identity");
20355
20356        synchronized (mPackages) {
20357            return mSettings.getVerifierDeviceIdentityLPw();
20358        }
20359    }
20360
20361    @Override
20362    public void setPermissionEnforced(String permission, boolean enforced) {
20363        // TODO: Now that we no longer change GID for storage, this should to away.
20364        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20365                "setPermissionEnforced");
20366        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20367            synchronized (mPackages) {
20368                if (mSettings.mReadExternalStorageEnforced == null
20369                        || mSettings.mReadExternalStorageEnforced != enforced) {
20370                    mSettings.mReadExternalStorageEnforced = enforced;
20371                    mSettings.writeLPr();
20372                }
20373            }
20374            // kill any non-foreground processes so we restart them and
20375            // grant/revoke the GID.
20376            final IActivityManager am = ActivityManagerNative.getDefault();
20377            if (am != null) {
20378                final long token = Binder.clearCallingIdentity();
20379                try {
20380                    am.killProcessesBelowForeground("setPermissionEnforcement");
20381                } catch (RemoteException e) {
20382                } finally {
20383                    Binder.restoreCallingIdentity(token);
20384                }
20385            }
20386        } else {
20387            throw new IllegalArgumentException("No selective enforcement for " + permission);
20388        }
20389    }
20390
20391    @Override
20392    @Deprecated
20393    public boolean isPermissionEnforced(String permission) {
20394        return true;
20395    }
20396
20397    @Override
20398    public boolean isStorageLow() {
20399        final long token = Binder.clearCallingIdentity();
20400        try {
20401            final DeviceStorageMonitorInternal
20402                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20403            if (dsm != null) {
20404                return dsm.isMemoryLow();
20405            } else {
20406                return false;
20407            }
20408        } finally {
20409            Binder.restoreCallingIdentity(token);
20410        }
20411    }
20412
20413    @Override
20414    public IPackageInstaller getPackageInstaller() {
20415        return mInstallerService;
20416    }
20417
20418    private boolean userNeedsBadging(int userId) {
20419        int index = mUserNeedsBadging.indexOfKey(userId);
20420        if (index < 0) {
20421            final UserInfo userInfo;
20422            final long token = Binder.clearCallingIdentity();
20423            try {
20424                userInfo = sUserManager.getUserInfo(userId);
20425            } finally {
20426                Binder.restoreCallingIdentity(token);
20427            }
20428            final boolean b;
20429            if (userInfo != null && userInfo.isManagedProfile()) {
20430                b = true;
20431            } else {
20432                b = false;
20433            }
20434            mUserNeedsBadging.put(userId, b);
20435            return b;
20436        }
20437        return mUserNeedsBadging.valueAt(index);
20438    }
20439
20440    @Override
20441    public KeySet getKeySetByAlias(String packageName, String alias) {
20442        if (packageName == null || alias == null) {
20443            return null;
20444        }
20445        synchronized(mPackages) {
20446            final PackageParser.Package pkg = mPackages.get(packageName);
20447            if (pkg == null) {
20448                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20449                throw new IllegalArgumentException("Unknown package: " + packageName);
20450            }
20451            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20452            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20453        }
20454    }
20455
20456    @Override
20457    public KeySet getSigningKeySet(String packageName) {
20458        if (packageName == null) {
20459            return null;
20460        }
20461        synchronized(mPackages) {
20462            final PackageParser.Package pkg = mPackages.get(packageName);
20463            if (pkg == null) {
20464                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20465                throw new IllegalArgumentException("Unknown package: " + packageName);
20466            }
20467            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20468                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20469                throw new SecurityException("May not access signing KeySet of other apps.");
20470            }
20471            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20472            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20473        }
20474    }
20475
20476    @Override
20477    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20478        if (packageName == null || ks == null) {
20479            return false;
20480        }
20481        synchronized(mPackages) {
20482            final PackageParser.Package pkg = mPackages.get(packageName);
20483            if (pkg == null) {
20484                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20485                throw new IllegalArgumentException("Unknown package: " + packageName);
20486            }
20487            IBinder ksh = ks.getToken();
20488            if (ksh instanceof KeySetHandle) {
20489                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20490                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20491            }
20492            return false;
20493        }
20494    }
20495
20496    @Override
20497    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20498        if (packageName == null || ks == null) {
20499            return false;
20500        }
20501        synchronized(mPackages) {
20502            final PackageParser.Package pkg = mPackages.get(packageName);
20503            if (pkg == null) {
20504                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20505                throw new IllegalArgumentException("Unknown package: " + packageName);
20506            }
20507            IBinder ksh = ks.getToken();
20508            if (ksh instanceof KeySetHandle) {
20509                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20510                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20511            }
20512            return false;
20513        }
20514    }
20515
20516    private void deletePackageIfUnusedLPr(final String packageName) {
20517        PackageSetting ps = mSettings.mPackages.get(packageName);
20518        if (ps == null) {
20519            return;
20520        }
20521        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20522            // TODO Implement atomic delete if package is unused
20523            // It is currently possible that the package will be deleted even if it is installed
20524            // after this method returns.
20525            mHandler.post(new Runnable() {
20526                public void run() {
20527                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20528                }
20529            });
20530        }
20531    }
20532
20533    /**
20534     * Check and throw if the given before/after packages would be considered a
20535     * downgrade.
20536     */
20537    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20538            throws PackageManagerException {
20539        if (after.versionCode < before.mVersionCode) {
20540            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20541                    "Update version code " + after.versionCode + " is older than current "
20542                    + before.mVersionCode);
20543        } else if (after.versionCode == before.mVersionCode) {
20544            if (after.baseRevisionCode < before.baseRevisionCode) {
20545                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20546                        "Update base revision code " + after.baseRevisionCode
20547                        + " is older than current " + before.baseRevisionCode);
20548            }
20549
20550            if (!ArrayUtils.isEmpty(after.splitNames)) {
20551                for (int i = 0; i < after.splitNames.length; i++) {
20552                    final String splitName = after.splitNames[i];
20553                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20554                    if (j != -1) {
20555                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20556                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20557                                    "Update split " + splitName + " revision code "
20558                                    + after.splitRevisionCodes[i] + " is older than current "
20559                                    + before.splitRevisionCodes[j]);
20560                        }
20561                    }
20562                }
20563            }
20564        }
20565    }
20566
20567    private static class MoveCallbacks extends Handler {
20568        private static final int MSG_CREATED = 1;
20569        private static final int MSG_STATUS_CHANGED = 2;
20570
20571        private final RemoteCallbackList<IPackageMoveObserver>
20572                mCallbacks = new RemoteCallbackList<>();
20573
20574        private final SparseIntArray mLastStatus = new SparseIntArray();
20575
20576        public MoveCallbacks(Looper looper) {
20577            super(looper);
20578        }
20579
20580        public void register(IPackageMoveObserver callback) {
20581            mCallbacks.register(callback);
20582        }
20583
20584        public void unregister(IPackageMoveObserver callback) {
20585            mCallbacks.unregister(callback);
20586        }
20587
20588        @Override
20589        public void handleMessage(Message msg) {
20590            final SomeArgs args = (SomeArgs) msg.obj;
20591            final int n = mCallbacks.beginBroadcast();
20592            for (int i = 0; i < n; i++) {
20593                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20594                try {
20595                    invokeCallback(callback, msg.what, args);
20596                } catch (RemoteException ignored) {
20597                }
20598            }
20599            mCallbacks.finishBroadcast();
20600            args.recycle();
20601        }
20602
20603        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20604                throws RemoteException {
20605            switch (what) {
20606                case MSG_CREATED: {
20607                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20608                    break;
20609                }
20610                case MSG_STATUS_CHANGED: {
20611                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20612                    break;
20613                }
20614            }
20615        }
20616
20617        private void notifyCreated(int moveId, Bundle extras) {
20618            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20619
20620            final SomeArgs args = SomeArgs.obtain();
20621            args.argi1 = moveId;
20622            args.arg2 = extras;
20623            obtainMessage(MSG_CREATED, args).sendToTarget();
20624        }
20625
20626        private void notifyStatusChanged(int moveId, int status) {
20627            notifyStatusChanged(moveId, status, -1);
20628        }
20629
20630        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20631            Slog.v(TAG, "Move " + moveId + " status " + status);
20632
20633            final SomeArgs args = SomeArgs.obtain();
20634            args.argi1 = moveId;
20635            args.argi2 = status;
20636            args.arg3 = estMillis;
20637            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20638
20639            synchronized (mLastStatus) {
20640                mLastStatus.put(moveId, status);
20641            }
20642        }
20643    }
20644
20645    private final static class OnPermissionChangeListeners extends Handler {
20646        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20647
20648        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20649                new RemoteCallbackList<>();
20650
20651        public OnPermissionChangeListeners(Looper looper) {
20652            super(looper);
20653        }
20654
20655        @Override
20656        public void handleMessage(Message msg) {
20657            switch (msg.what) {
20658                case MSG_ON_PERMISSIONS_CHANGED: {
20659                    final int uid = msg.arg1;
20660                    handleOnPermissionsChanged(uid);
20661                } break;
20662            }
20663        }
20664
20665        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20666            mPermissionListeners.register(listener);
20667
20668        }
20669
20670        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20671            mPermissionListeners.unregister(listener);
20672        }
20673
20674        public void onPermissionsChanged(int uid) {
20675            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20676                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20677            }
20678        }
20679
20680        private void handleOnPermissionsChanged(int uid) {
20681            final int count = mPermissionListeners.beginBroadcast();
20682            try {
20683                for (int i = 0; i < count; i++) {
20684                    IOnPermissionsChangeListener callback = mPermissionListeners
20685                            .getBroadcastItem(i);
20686                    try {
20687                        callback.onPermissionsChanged(uid);
20688                    } catch (RemoteException e) {
20689                        Log.e(TAG, "Permission listener is dead", e);
20690                    }
20691                }
20692            } finally {
20693                mPermissionListeners.finishBroadcast();
20694            }
20695        }
20696    }
20697
20698    private class PackageManagerInternalImpl extends PackageManagerInternal {
20699        @Override
20700        public void setLocationPackagesProvider(PackagesProvider provider) {
20701            synchronized (mPackages) {
20702                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20703            }
20704        }
20705
20706        @Override
20707        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20708            synchronized (mPackages) {
20709                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20710            }
20711        }
20712
20713        @Override
20714        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20715            synchronized (mPackages) {
20716                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20717            }
20718        }
20719
20720        @Override
20721        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20722            synchronized (mPackages) {
20723                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20724            }
20725        }
20726
20727        @Override
20728        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20729            synchronized (mPackages) {
20730                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20731            }
20732        }
20733
20734        @Override
20735        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20736            synchronized (mPackages) {
20737                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20738            }
20739        }
20740
20741        @Override
20742        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20743            synchronized (mPackages) {
20744                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20745                        packageName, userId);
20746            }
20747        }
20748
20749        @Override
20750        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20751            synchronized (mPackages) {
20752                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20753                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20754                        packageName, userId);
20755            }
20756        }
20757
20758        @Override
20759        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20760            synchronized (mPackages) {
20761                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20762                        packageName, userId);
20763            }
20764        }
20765
20766        @Override
20767        public void setKeepUninstalledPackages(final List<String> packageList) {
20768            Preconditions.checkNotNull(packageList);
20769            List<String> removedFromList = null;
20770            synchronized (mPackages) {
20771                if (mKeepUninstalledPackages != null) {
20772                    final int packagesCount = mKeepUninstalledPackages.size();
20773                    for (int i = 0; i < packagesCount; i++) {
20774                        String oldPackage = mKeepUninstalledPackages.get(i);
20775                        if (packageList != null && packageList.contains(oldPackage)) {
20776                            continue;
20777                        }
20778                        if (removedFromList == null) {
20779                            removedFromList = new ArrayList<>();
20780                        }
20781                        removedFromList.add(oldPackage);
20782                    }
20783                }
20784                mKeepUninstalledPackages = new ArrayList<>(packageList);
20785                if (removedFromList != null) {
20786                    final int removedCount = removedFromList.size();
20787                    for (int i = 0; i < removedCount; i++) {
20788                        deletePackageIfUnusedLPr(removedFromList.get(i));
20789                    }
20790                }
20791            }
20792        }
20793
20794        @Override
20795        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20796            synchronized (mPackages) {
20797                // If we do not support permission review, done.
20798                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20799                    return false;
20800                }
20801
20802                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20803                if (packageSetting == null) {
20804                    return false;
20805                }
20806
20807                // Permission review applies only to apps not supporting the new permission model.
20808                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20809                    return false;
20810                }
20811
20812                // Legacy apps have the permission and get user consent on launch.
20813                PermissionsState permissionsState = packageSetting.getPermissionsState();
20814                return permissionsState.isPermissionReviewRequired(userId);
20815            }
20816        }
20817
20818        @Override
20819        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20820            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20821        }
20822
20823        @Override
20824        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20825                int userId) {
20826            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20827        }
20828    }
20829
20830    @Override
20831    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20832        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20833        synchronized (mPackages) {
20834            final long identity = Binder.clearCallingIdentity();
20835            try {
20836                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20837                        packageNames, userId);
20838            } finally {
20839                Binder.restoreCallingIdentity(identity);
20840            }
20841        }
20842    }
20843
20844    private static void enforceSystemOrPhoneCaller(String tag) {
20845        int callingUid = Binder.getCallingUid();
20846        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20847            throw new SecurityException(
20848                    "Cannot call " + tag + " from UID " + callingUid);
20849        }
20850    }
20851
20852    boolean isHistoricalPackageUsageAvailable() {
20853        return mPackageUsage.isHistoricalPackageUsageAvailable();
20854    }
20855
20856    /**
20857     * Return a <b>copy</b> of the collection of packages known to the package manager.
20858     * @return A copy of the values of mPackages.
20859     */
20860    Collection<PackageParser.Package> getPackages() {
20861        synchronized (mPackages) {
20862            return new ArrayList<>(mPackages.values());
20863        }
20864    }
20865
20866    /**
20867     * Logs process start information (including base APK hash) to the security log.
20868     * @hide
20869     */
20870    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20871            String apkFile, int pid) {
20872        if (!SecurityLog.isLoggingEnabled()) {
20873            return;
20874        }
20875        Bundle data = new Bundle();
20876        data.putLong("startTimestamp", System.currentTimeMillis());
20877        data.putString("processName", processName);
20878        data.putInt("uid", uid);
20879        data.putString("seinfo", seinfo);
20880        data.putString("apkFile", apkFile);
20881        data.putInt("pid", pid);
20882        Message msg = mProcessLoggingHandler.obtainMessage(
20883                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20884        msg.setData(data);
20885        mProcessLoggingHandler.sendMessage(msg);
20886    }
20887}
20888