PackageManagerService.java revision 83dce3642abb44fb83384a2e95ce2b89bfd80e20
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.annotation.UserIdInt;
106import android.app.ActivityManager;
107import android.app.ActivityManagerNative;
108import android.app.IActivityManager;
109import android.app.ResourcesManager;
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    final ProtectedPackages mProtectedPackages = new ProtectedPackages();
626
627    boolean mRestoredSettings;
628
629    // System configuration read by SystemConfig.
630    final int[] mGlobalGids;
631    final SparseArray<ArraySet<String>> mSystemPermissions;
632    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
633
634    // If mac_permissions.xml was found for seinfo labeling.
635    boolean mFoundPolicyFile;
636
637    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
638
639    public static final class SharedLibraryEntry {
640        public final String path;
641        public final String apk;
642
643        SharedLibraryEntry(String _path, String _apk) {
644            path = _path;
645            apk = _apk;
646        }
647    }
648
649    // Currently known shared libraries.
650    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
651            new ArrayMap<String, SharedLibraryEntry>();
652
653    // All available activities, for your resolving pleasure.
654    final ActivityIntentResolver mActivities =
655            new ActivityIntentResolver();
656
657    // All available receivers, for your resolving pleasure.
658    final ActivityIntentResolver mReceivers =
659            new ActivityIntentResolver();
660
661    // All available services, for your resolving pleasure.
662    final ServiceIntentResolver mServices = new ServiceIntentResolver();
663
664    // All available providers, for your resolving pleasure.
665    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
666
667    // Mapping from provider base names (first directory in content URI codePath)
668    // to the provider information.
669    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
670            new ArrayMap<String, PackageParser.Provider>();
671
672    // Mapping from instrumentation class names to info about them.
673    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
674            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
675
676    // Mapping from permission names to info about them.
677    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
678            new ArrayMap<String, PackageParser.PermissionGroup>();
679
680    // Packages whose data we have transfered into another package, thus
681    // should no longer exist.
682    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
683
684    // Broadcast actions that are only available to the system.
685    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
686
687    /** List of packages waiting for verification. */
688    final SparseArray<PackageVerificationState> mPendingVerification
689            = new SparseArray<PackageVerificationState>();
690
691    /** Set of packages associated with each app op permission. */
692    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
693
694    final PackageInstallerService mInstallerService;
695
696    private final PackageDexOptimizer mPackageDexOptimizer;
697
698    private AtomicInteger mNextMoveId = new AtomicInteger();
699    private final MoveCallbacks mMoveCallbacks;
700
701    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
702
703    // Cache of users who need badging.
704    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
705
706    /** Token for keys in mPendingVerification. */
707    private int mPendingVerificationToken = 0;
708
709    volatile boolean mSystemReady;
710    volatile boolean mSafeMode;
711    volatile boolean mHasSystemUidErrors;
712
713    ApplicationInfo mAndroidApplication;
714    final ActivityInfo mResolveActivity = new ActivityInfo();
715    final ResolveInfo mResolveInfo = new ResolveInfo();
716    ComponentName mResolveComponentName;
717    PackageParser.Package mPlatformPackage;
718    ComponentName mCustomResolverComponentName;
719
720    boolean mResolverReplaced = false;
721
722    private final @Nullable ComponentName mIntentFilterVerifierComponent;
723    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
724
725    private int mIntentFilterVerificationToken = 0;
726
727    /** Component that knows whether or not an ephemeral application exists */
728    final ComponentName mEphemeralResolverComponent;
729    /** The service connection to the ephemeral resolver */
730    final EphemeralResolverConnection mEphemeralResolverConnection;
731
732    /** Component used to install ephemeral applications */
733    final ComponentName mEphemeralInstallerComponent;
734    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
735    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
736
737    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
738            = new SparseArray<IntentFilterVerificationState>();
739
740    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
741            new DefaultPermissionGrantPolicy(this);
742
743    // List of packages names to keep cached, even if they are uninstalled for all users
744    private List<String> mKeepUninstalledPackages;
745
746    private UserManagerInternal mUserManagerInternal;
747
748    private static class IFVerificationParams {
749        PackageParser.Package pkg;
750        boolean replacing;
751        int userId;
752        int verifierUid;
753
754        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
755                int _userId, int _verifierUid) {
756            pkg = _pkg;
757            replacing = _replacing;
758            userId = _userId;
759            replacing = _replacing;
760            verifierUid = _verifierUid;
761        }
762    }
763
764    private interface IntentFilterVerifier<T extends IntentFilter> {
765        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
766                                               T filter, String packageName);
767        void startVerifications(int userId);
768        void receiveVerificationResponse(int verificationId);
769    }
770
771    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
772        private Context mContext;
773        private ComponentName mIntentFilterVerifierComponent;
774        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
775
776        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
777            mContext = context;
778            mIntentFilterVerifierComponent = verifierComponent;
779        }
780
781        private String getDefaultScheme() {
782            return IntentFilter.SCHEME_HTTPS;
783        }
784
785        @Override
786        public void startVerifications(int userId) {
787            // Launch verifications requests
788            int count = mCurrentIntentFilterVerifications.size();
789            for (int n=0; n<count; n++) {
790                int verificationId = mCurrentIntentFilterVerifications.get(n);
791                final IntentFilterVerificationState ivs =
792                        mIntentFilterVerificationStates.get(verificationId);
793
794                String packageName = ivs.getPackageName();
795
796                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
797                final int filterCount = filters.size();
798                ArraySet<String> domainsSet = new ArraySet<>();
799                for (int m=0; m<filterCount; m++) {
800                    PackageParser.ActivityIntentInfo filter = filters.get(m);
801                    domainsSet.addAll(filter.getHostsList());
802                }
803                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
804                synchronized (mPackages) {
805                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
806                            packageName, domainsList) != null) {
807                        scheduleWriteSettingsLocked();
808                    }
809                }
810                sendVerificationRequest(userId, verificationId, ivs);
811            }
812            mCurrentIntentFilterVerifications.clear();
813        }
814
815        private void sendVerificationRequest(int userId, int verificationId,
816                IntentFilterVerificationState ivs) {
817
818            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
819            verificationIntent.putExtra(
820                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
821                    verificationId);
822            verificationIntent.putExtra(
823                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
824                    getDefaultScheme());
825            verificationIntent.putExtra(
826                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
827                    ivs.getHostsString());
828            verificationIntent.putExtra(
829                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
830                    ivs.getPackageName());
831            verificationIntent.setComponent(mIntentFilterVerifierComponent);
832            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
833
834            UserHandle user = new UserHandle(userId);
835            mContext.sendBroadcastAsUser(verificationIntent, user);
836            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
837                    "Sending IntentFilter verification broadcast");
838        }
839
840        public void receiveVerificationResponse(int verificationId) {
841            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
842
843            final boolean verified = ivs.isVerified();
844
845            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
846            final int count = filters.size();
847            if (DEBUG_DOMAIN_VERIFICATION) {
848                Slog.i(TAG, "Received verification response " + verificationId
849                        + " for " + count + " filters, verified=" + verified);
850            }
851            for (int n=0; n<count; n++) {
852                PackageParser.ActivityIntentInfo filter = filters.get(n);
853                filter.setVerified(verified);
854
855                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
856                        + " verified with result:" + verified + " and hosts:"
857                        + ivs.getHostsString());
858            }
859
860            mIntentFilterVerificationStates.remove(verificationId);
861
862            final String packageName = ivs.getPackageName();
863            IntentFilterVerificationInfo ivi = null;
864
865            synchronized (mPackages) {
866                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
867            }
868            if (ivi == null) {
869                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
870                        + verificationId + " packageName:" + packageName);
871                return;
872            }
873            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
874                    "Updating IntentFilterVerificationInfo for package " + packageName
875                            +" verificationId:" + verificationId);
876
877            synchronized (mPackages) {
878                if (verified) {
879                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
880                } else {
881                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
882                }
883                scheduleWriteSettingsLocked();
884
885                final int userId = ivs.getUserId();
886                if (userId != UserHandle.USER_ALL) {
887                    final int userStatus =
888                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
889
890                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
891                    boolean needUpdate = false;
892
893                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
894                    // already been set by the User thru the Disambiguation dialog
895                    switch (userStatus) {
896                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
897                            if (verified) {
898                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
899                            } else {
900                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
901                            }
902                            needUpdate = true;
903                            break;
904
905                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
906                            if (verified) {
907                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
908                                needUpdate = true;
909                            }
910                            break;
911
912                        default:
913                            // Nothing to do
914                    }
915
916                    if (needUpdate) {
917                        mSettings.updateIntentFilterVerificationStatusLPw(
918                                packageName, updatedStatus, userId);
919                        scheduleWritePackageRestrictionsLocked(userId);
920                    }
921                }
922            }
923        }
924
925        @Override
926        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
927                    ActivityIntentInfo filter, String packageName) {
928            if (!hasValidDomains(filter)) {
929                return false;
930            }
931            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
932            if (ivs == null) {
933                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
934                        packageName);
935            }
936            if (DEBUG_DOMAIN_VERIFICATION) {
937                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
938            }
939            ivs.addFilter(filter);
940            return true;
941        }
942
943        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
944                int userId, int verificationId, String packageName) {
945            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
946                    verifierUid, userId, packageName);
947            ivs.setPendingState();
948            synchronized (mPackages) {
949                mIntentFilterVerificationStates.append(verificationId, ivs);
950                mCurrentIntentFilterVerifications.add(verificationId);
951            }
952            return ivs;
953        }
954    }
955
956    private static boolean hasValidDomains(ActivityIntentInfo filter) {
957        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
958                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
959                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
960    }
961
962    // Set of pending broadcasts for aggregating enable/disable of components.
963    static class PendingPackageBroadcasts {
964        // for each user id, a map of <package name -> components within that package>
965        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
966
967        public PendingPackageBroadcasts() {
968            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
969        }
970
971        public ArrayList<String> get(int userId, String packageName) {
972            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
973            return packages.get(packageName);
974        }
975
976        public void put(int userId, String packageName, ArrayList<String> components) {
977            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
978            packages.put(packageName, components);
979        }
980
981        public void remove(int userId, String packageName) {
982            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
983            if (packages != null) {
984                packages.remove(packageName);
985            }
986        }
987
988        public void remove(int userId) {
989            mUidMap.remove(userId);
990        }
991
992        public int userIdCount() {
993            return mUidMap.size();
994        }
995
996        public int userIdAt(int n) {
997            return mUidMap.keyAt(n);
998        }
999
1000        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1001            return mUidMap.get(userId);
1002        }
1003
1004        public int size() {
1005            // total number of pending broadcast entries across all userIds
1006            int num = 0;
1007            for (int i = 0; i< mUidMap.size(); i++) {
1008                num += mUidMap.valueAt(i).size();
1009            }
1010            return num;
1011        }
1012
1013        public void clear() {
1014            mUidMap.clear();
1015        }
1016
1017        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1018            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1019            if (map == null) {
1020                map = new ArrayMap<String, ArrayList<String>>();
1021                mUidMap.put(userId, map);
1022            }
1023            return map;
1024        }
1025    }
1026    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1027
1028    // Service Connection to remote media container service to copy
1029    // package uri's from external media onto secure containers
1030    // or internal storage.
1031    private IMediaContainerService mContainerService = null;
1032
1033    static final int SEND_PENDING_BROADCAST = 1;
1034    static final int MCS_BOUND = 3;
1035    static final int END_COPY = 4;
1036    static final int INIT_COPY = 5;
1037    static final int MCS_UNBIND = 6;
1038    static final int START_CLEANING_PACKAGE = 7;
1039    static final int FIND_INSTALL_LOC = 8;
1040    static final int POST_INSTALL = 9;
1041    static final int MCS_RECONNECT = 10;
1042    static final int MCS_GIVE_UP = 11;
1043    static final int UPDATED_MEDIA_STATUS = 12;
1044    static final int WRITE_SETTINGS = 13;
1045    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1046    static final int PACKAGE_VERIFIED = 15;
1047    static final int CHECK_PENDING_VERIFICATION = 16;
1048    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1049    static final int INTENT_FILTER_VERIFIED = 18;
1050    static final int WRITE_PACKAGE_LIST = 19;
1051
1052    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1053
1054    // Delay time in millisecs
1055    static final int BROADCAST_DELAY = 10 * 1000;
1056
1057    static UserManagerService sUserManager;
1058
1059    // Stores a list of users whose package restrictions file needs to be updated
1060    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1061
1062    final private DefaultContainerConnection mDefContainerConn =
1063            new DefaultContainerConnection();
1064    class DefaultContainerConnection implements ServiceConnection {
1065        public void onServiceConnected(ComponentName name, IBinder service) {
1066            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1067            IMediaContainerService imcs =
1068                IMediaContainerService.Stub.asInterface(service);
1069            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1070        }
1071
1072        public void onServiceDisconnected(ComponentName name) {
1073            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1074        }
1075    }
1076
1077    // Recordkeeping of restore-after-install operations that are currently in flight
1078    // between the Package Manager and the Backup Manager
1079    static class PostInstallData {
1080        public InstallArgs args;
1081        public PackageInstalledInfo res;
1082
1083        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1084            args = _a;
1085            res = _r;
1086        }
1087    }
1088
1089    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1090    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1091
1092    // XML tags for backup/restore of various bits of state
1093    private static final String TAG_PREFERRED_BACKUP = "pa";
1094    private static final String TAG_DEFAULT_APPS = "da";
1095    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1096
1097    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1098    private static final String TAG_ALL_GRANTS = "rt-grants";
1099    private static final String TAG_GRANT = "grant";
1100    private static final String ATTR_PACKAGE_NAME = "pkg";
1101
1102    private static final String TAG_PERMISSION = "perm";
1103    private static final String ATTR_PERMISSION_NAME = "name";
1104    private static final String ATTR_IS_GRANTED = "g";
1105    private static final String ATTR_USER_SET = "set";
1106    private static final String ATTR_USER_FIXED = "fixed";
1107    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1108
1109    // System/policy permission grants are not backed up
1110    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1111            FLAG_PERMISSION_POLICY_FIXED
1112            | FLAG_PERMISSION_SYSTEM_FIXED
1113            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1114
1115    // And we back up these user-adjusted states
1116    private static final int USER_RUNTIME_GRANT_MASK =
1117            FLAG_PERMISSION_USER_SET
1118            | FLAG_PERMISSION_USER_FIXED
1119            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1120
1121    final @Nullable String mRequiredVerifierPackage;
1122    final @NonNull String mRequiredInstallerPackage;
1123    final @Nullable String mSetupWizardPackage;
1124    final @NonNull String mServicesSystemSharedLibraryPackageName;
1125    final @NonNull String mSharedSystemSharedLibraryPackageName;
1126
1127    private final PackageUsage mPackageUsage = new PackageUsage();
1128
1129    private class PackageUsage {
1130        private static final int WRITE_INTERVAL
1131            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1132
1133        private final Object mFileLock = new Object();
1134        private final AtomicLong mLastWritten = new AtomicLong(0);
1135        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1136
1137        private boolean mIsHistoricalPackageUsageAvailable = true;
1138
1139        boolean isHistoricalPackageUsageAvailable() {
1140            return mIsHistoricalPackageUsageAvailable;
1141        }
1142
1143        void write(boolean force) {
1144            if (force) {
1145                writeInternal();
1146                return;
1147            }
1148            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1149                && !DEBUG_DEXOPT) {
1150                return;
1151            }
1152            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1153                new Thread("PackageUsage_DiskWriter") {
1154                    @Override
1155                    public void run() {
1156                        try {
1157                            writeInternal();
1158                        } finally {
1159                            mBackgroundWriteRunning.set(false);
1160                        }
1161                    }
1162                }.start();
1163            }
1164        }
1165
1166        private void writeInternal() {
1167            synchronized (mPackages) {
1168                synchronized (mFileLock) {
1169                    AtomicFile file = getFile();
1170                    FileOutputStream f = null;
1171                    try {
1172                        f = file.startWrite();
1173                        BufferedOutputStream out = new BufferedOutputStream(f);
1174                        FileUtils.setPermissions(file.getBaseFile().getPath(),
1175                                0640, SYSTEM_UID, PACKAGE_INFO_GID);
1176                        StringBuilder sb = new StringBuilder();
1177
1178                        sb.append(USAGE_FILE_MAGIC_VERSION_1);
1179                        sb.append('\n');
1180                        out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1181
1182                        for (PackageParser.Package pkg : mPackages.values()) {
1183                            if (pkg.getLatestPackageUseTimeInMills() == 0L) {
1184                                continue;
1185                            }
1186                            sb.setLength(0);
1187                            sb.append(pkg.packageName);
1188                            for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) {
1189                                sb.append(' ');
1190                                sb.append(usageTimeInMillis);
1191                            }
1192                            sb.append('\n');
1193                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1194                        }
1195                        out.flush();
1196                        file.finishWrite(f);
1197                    } catch (IOException e) {
1198                        if (f != null) {
1199                            file.failWrite(f);
1200                        }
1201                        Log.e(TAG, "Failed to write package usage times", e);
1202                    }
1203                }
1204            }
1205            mLastWritten.set(SystemClock.elapsedRealtime());
1206        }
1207
1208        void readLP() {
1209            synchronized (mFileLock) {
1210                AtomicFile file = getFile();
1211                BufferedInputStream in = null;
1212                try {
1213                    in = new BufferedInputStream(file.openRead());
1214                    StringBuffer sb = new StringBuffer();
1215
1216                    String firstLine = readLine(in, sb);
1217                    if (firstLine == null) {
1218                        // Empty file. Do nothing.
1219                    } else if (USAGE_FILE_MAGIC_VERSION_1.equals(firstLine)) {
1220                        readVersion1LP(in, sb);
1221                    } else {
1222                        readVersion0LP(in, sb, firstLine);
1223                    }
1224                } catch (FileNotFoundException expected) {
1225                    mIsHistoricalPackageUsageAvailable = false;
1226                } catch (IOException e) {
1227                    Log.w(TAG, "Failed to read package usage times", e);
1228                } finally {
1229                    IoUtils.closeQuietly(in);
1230                }
1231            }
1232            mLastWritten.set(SystemClock.elapsedRealtime());
1233        }
1234
1235        private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine)
1236                throws IOException {
1237            // Initial version of the file had no version number and stored one
1238            // package-timestamp pair per line.
1239            // Note that the first line has already been read from the InputStream.
1240            for (String line = firstLine; line != null; line = readLine(in, sb)) {
1241                String[] tokens = line.split(" ");
1242                if (tokens.length != 2) {
1243                    throw new IOException("Failed to parse " + line +
1244                            " as package-timestamp pair.");
1245                }
1246
1247                String packageName = tokens[0];
1248                PackageParser.Package pkg = mPackages.get(packageName);
1249                if (pkg == null) {
1250                    continue;
1251                }
1252
1253                long timestamp = parseAsLong(tokens[1]);
1254                for (int reason = 0;
1255                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1256                        reason++) {
1257                    pkg.mLastPackageUsageTimeInMills[reason] = timestamp;
1258                }
1259            }
1260        }
1261
1262        private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException {
1263            // Version 1 of the file started with the corresponding version
1264            // number and then stored a package name and eight timestamps per line.
1265            String line;
1266            while ((line = readLine(in, sb)) != null) {
1267                String[] tokens = line.split(" ");
1268                if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) {
1269                    throw new IOException("Failed to parse " + line + " as a timestamp array.");
1270                }
1271
1272                String packageName = tokens[0];
1273                PackageParser.Package pkg = mPackages.get(packageName);
1274                if (pkg == null) {
1275                    continue;
1276                }
1277
1278                for (int reason = 0;
1279                        reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT;
1280                        reason++) {
1281                    pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]);
1282                }
1283            }
1284        }
1285
1286        private long parseAsLong(String token) throws IOException {
1287            try {
1288                return Long.parseLong(token);
1289            } catch (NumberFormatException e) {
1290                throw new IOException("Failed to parse " + token + " as a long.", e);
1291            }
1292        }
1293
1294        private String readLine(InputStream in, StringBuffer sb) throws IOException {
1295            return readToken(in, sb, '\n');
1296        }
1297
1298        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1299                throws IOException {
1300            sb.setLength(0);
1301            while (true) {
1302                int ch = in.read();
1303                if (ch == -1) {
1304                    if (sb.length() == 0) {
1305                        return null;
1306                    }
1307                    throw new IOException("Unexpected EOF");
1308                }
1309                if (ch == endOfToken) {
1310                    return sb.toString();
1311                }
1312                sb.append((char)ch);
1313            }
1314        }
1315
1316        private AtomicFile getFile() {
1317            File dataDir = Environment.getDataDirectory();
1318            File systemDir = new File(dataDir, "system");
1319            File fname = new File(systemDir, "package-usage.list");
1320            return new AtomicFile(fname);
1321        }
1322
1323        private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_";
1324        private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1";
1325    }
1326
1327    class PackageHandler extends Handler {
1328        private boolean mBound = false;
1329        final ArrayList<HandlerParams> mPendingInstalls =
1330            new ArrayList<HandlerParams>();
1331
1332        private boolean connectToService() {
1333            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1334                    " DefaultContainerService");
1335            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1336            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1337            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1338                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1339                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1340                mBound = true;
1341                return true;
1342            }
1343            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1344            return false;
1345        }
1346
1347        private void disconnectService() {
1348            mContainerService = null;
1349            mBound = false;
1350            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1351            mContext.unbindService(mDefContainerConn);
1352            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1353        }
1354
1355        PackageHandler(Looper looper) {
1356            super(looper);
1357        }
1358
1359        public void handleMessage(Message msg) {
1360            try {
1361                doHandleMessage(msg);
1362            } finally {
1363                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1364            }
1365        }
1366
1367        void doHandleMessage(Message msg) {
1368            switch (msg.what) {
1369                case INIT_COPY: {
1370                    HandlerParams params = (HandlerParams) msg.obj;
1371                    int idx = mPendingInstalls.size();
1372                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1373                    // If a bind was already initiated we dont really
1374                    // need to do anything. The pending install
1375                    // will be processed later on.
1376                    if (!mBound) {
1377                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1378                                System.identityHashCode(mHandler));
1379                        // If this is the only one pending we might
1380                        // have to bind to the service again.
1381                        if (!connectToService()) {
1382                            Slog.e(TAG, "Failed to bind to media container service");
1383                            params.serviceError();
1384                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1385                                    System.identityHashCode(mHandler));
1386                            if (params.traceMethod != null) {
1387                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1388                                        params.traceCookie);
1389                            }
1390                            return;
1391                        } else {
1392                            // Once we bind to the service, the first
1393                            // pending request will be processed.
1394                            mPendingInstalls.add(idx, params);
1395                        }
1396                    } else {
1397                        mPendingInstalls.add(idx, params);
1398                        // Already bound to the service. Just make
1399                        // sure we trigger off processing the first request.
1400                        if (idx == 0) {
1401                            mHandler.sendEmptyMessage(MCS_BOUND);
1402                        }
1403                    }
1404                    break;
1405                }
1406                case MCS_BOUND: {
1407                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1408                    if (msg.obj != null) {
1409                        mContainerService = (IMediaContainerService) msg.obj;
1410                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1411                                System.identityHashCode(mHandler));
1412                    }
1413                    if (mContainerService == null) {
1414                        if (!mBound) {
1415                            // Something seriously wrong since we are not bound and we are not
1416                            // waiting for connection. Bail out.
1417                            Slog.e(TAG, "Cannot bind to media container service");
1418                            for (HandlerParams params : mPendingInstalls) {
1419                                // Indicate service bind error
1420                                params.serviceError();
1421                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1422                                        System.identityHashCode(params));
1423                                if (params.traceMethod != null) {
1424                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1425                                            params.traceMethod, params.traceCookie);
1426                                }
1427                                return;
1428                            }
1429                            mPendingInstalls.clear();
1430                        } else {
1431                            Slog.w(TAG, "Waiting to connect to media container service");
1432                        }
1433                    } else if (mPendingInstalls.size() > 0) {
1434                        HandlerParams params = mPendingInstalls.get(0);
1435                        if (params != null) {
1436                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1437                                    System.identityHashCode(params));
1438                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1439                            if (params.startCopy()) {
1440                                // We are done...  look for more work or to
1441                                // go idle.
1442                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1443                                        "Checking for more work or unbind...");
1444                                // Delete pending install
1445                                if (mPendingInstalls.size() > 0) {
1446                                    mPendingInstalls.remove(0);
1447                                }
1448                                if (mPendingInstalls.size() == 0) {
1449                                    if (mBound) {
1450                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1451                                                "Posting delayed MCS_UNBIND");
1452                                        removeMessages(MCS_UNBIND);
1453                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1454                                        // Unbind after a little delay, to avoid
1455                                        // continual thrashing.
1456                                        sendMessageDelayed(ubmsg, 10000);
1457                                    }
1458                                } else {
1459                                    // There are more pending requests in queue.
1460                                    // Just post MCS_BOUND message to trigger processing
1461                                    // of next pending install.
1462                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1463                                            "Posting MCS_BOUND for next work");
1464                                    mHandler.sendEmptyMessage(MCS_BOUND);
1465                                }
1466                            }
1467                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1468                        }
1469                    } else {
1470                        // Should never happen ideally.
1471                        Slog.w(TAG, "Empty queue");
1472                    }
1473                    break;
1474                }
1475                case MCS_RECONNECT: {
1476                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1477                    if (mPendingInstalls.size() > 0) {
1478                        if (mBound) {
1479                            disconnectService();
1480                        }
1481                        if (!connectToService()) {
1482                            Slog.e(TAG, "Failed to bind to media container service");
1483                            for (HandlerParams params : mPendingInstalls) {
1484                                // Indicate service bind error
1485                                params.serviceError();
1486                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1487                                        System.identityHashCode(params));
1488                            }
1489                            mPendingInstalls.clear();
1490                        }
1491                    }
1492                    break;
1493                }
1494                case MCS_UNBIND: {
1495                    // If there is no actual work left, then time to unbind.
1496                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1497
1498                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1499                        if (mBound) {
1500                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1501
1502                            disconnectService();
1503                        }
1504                    } else if (mPendingInstalls.size() > 0) {
1505                        // There are more pending requests in queue.
1506                        // Just post MCS_BOUND message to trigger processing
1507                        // of next pending install.
1508                        mHandler.sendEmptyMessage(MCS_BOUND);
1509                    }
1510
1511                    break;
1512                }
1513                case MCS_GIVE_UP: {
1514                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1515                    HandlerParams params = mPendingInstalls.remove(0);
1516                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1517                            System.identityHashCode(params));
1518                    break;
1519                }
1520                case SEND_PENDING_BROADCAST: {
1521                    String packages[];
1522                    ArrayList<String> components[];
1523                    int size = 0;
1524                    int uids[];
1525                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1526                    synchronized (mPackages) {
1527                        if (mPendingBroadcasts == null) {
1528                            return;
1529                        }
1530                        size = mPendingBroadcasts.size();
1531                        if (size <= 0) {
1532                            // Nothing to be done. Just return
1533                            return;
1534                        }
1535                        packages = new String[size];
1536                        components = new ArrayList[size];
1537                        uids = new int[size];
1538                        int i = 0;  // filling out the above arrays
1539
1540                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1541                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1542                            Iterator<Map.Entry<String, ArrayList<String>>> it
1543                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1544                                            .entrySet().iterator();
1545                            while (it.hasNext() && i < size) {
1546                                Map.Entry<String, ArrayList<String>> ent = it.next();
1547                                packages[i] = ent.getKey();
1548                                components[i] = ent.getValue();
1549                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1550                                uids[i] = (ps != null)
1551                                        ? UserHandle.getUid(packageUserId, ps.appId)
1552                                        : -1;
1553                                i++;
1554                            }
1555                        }
1556                        size = i;
1557                        mPendingBroadcasts.clear();
1558                    }
1559                    // Send broadcasts
1560                    for (int i = 0; i < size; i++) {
1561                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1562                    }
1563                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1564                    break;
1565                }
1566                case START_CLEANING_PACKAGE: {
1567                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1568                    final String packageName = (String)msg.obj;
1569                    final int userId = msg.arg1;
1570                    final boolean andCode = msg.arg2 != 0;
1571                    synchronized (mPackages) {
1572                        if (userId == UserHandle.USER_ALL) {
1573                            int[] users = sUserManager.getUserIds();
1574                            for (int user : users) {
1575                                mSettings.addPackageToCleanLPw(
1576                                        new PackageCleanItem(user, packageName, andCode));
1577                            }
1578                        } else {
1579                            mSettings.addPackageToCleanLPw(
1580                                    new PackageCleanItem(userId, packageName, andCode));
1581                        }
1582                    }
1583                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1584                    startCleaningPackages();
1585                } break;
1586                case POST_INSTALL: {
1587                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1588
1589                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1590                    final boolean didRestore = (msg.arg2 != 0);
1591                    mRunningInstalls.delete(msg.arg1);
1592
1593                    if (data != null) {
1594                        InstallArgs args = data.args;
1595                        PackageInstalledInfo parentRes = data.res;
1596
1597                        final boolean grantPermissions = (args.installFlags
1598                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1599                        final boolean killApp = (args.installFlags
1600                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1601                        final String[] grantedPermissions = args.installGrantPermissions;
1602
1603                        // Handle the parent package
1604                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1605                                grantedPermissions, didRestore, args.installerPackageName,
1606                                args.observer);
1607
1608                        // Handle the child packages
1609                        final int childCount = (parentRes.addedChildPackages != null)
1610                                ? parentRes.addedChildPackages.size() : 0;
1611                        for (int i = 0; i < childCount; i++) {
1612                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1613                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1614                                    grantedPermissions, false, args.installerPackageName,
1615                                    args.observer);
1616                        }
1617
1618                        // Log tracing if needed
1619                        if (args.traceMethod != null) {
1620                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1621                                    args.traceCookie);
1622                        }
1623                    } else {
1624                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1625                    }
1626
1627                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1628                } break;
1629                case UPDATED_MEDIA_STATUS: {
1630                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1631                    boolean reportStatus = msg.arg1 == 1;
1632                    boolean doGc = msg.arg2 == 1;
1633                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1634                    if (doGc) {
1635                        // Force a gc to clear up stale containers.
1636                        Runtime.getRuntime().gc();
1637                    }
1638                    if (msg.obj != null) {
1639                        @SuppressWarnings("unchecked")
1640                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1641                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1642                        // Unload containers
1643                        unloadAllContainers(args);
1644                    }
1645                    if (reportStatus) {
1646                        try {
1647                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1648                            PackageHelper.getMountService().finishMediaUpdate();
1649                        } catch (RemoteException e) {
1650                            Log.e(TAG, "MountService not running?");
1651                        }
1652                    }
1653                } break;
1654                case WRITE_SETTINGS: {
1655                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1656                    synchronized (mPackages) {
1657                        removeMessages(WRITE_SETTINGS);
1658                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1659                        mSettings.writeLPr();
1660                        mDirtyUsers.clear();
1661                    }
1662                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1663                } break;
1664                case WRITE_PACKAGE_RESTRICTIONS: {
1665                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1666                    synchronized (mPackages) {
1667                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1668                        for (int userId : mDirtyUsers) {
1669                            mSettings.writePackageRestrictionsLPr(userId);
1670                        }
1671                        mDirtyUsers.clear();
1672                    }
1673                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1674                } break;
1675                case WRITE_PACKAGE_LIST: {
1676                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1677                    synchronized (mPackages) {
1678                        removeMessages(WRITE_PACKAGE_LIST);
1679                        mSettings.writePackageListLPr(msg.arg1);
1680                    }
1681                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1682                } break;
1683                case CHECK_PENDING_VERIFICATION: {
1684                    final int verificationId = msg.arg1;
1685                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1686
1687                    if ((state != null) && !state.timeoutExtended()) {
1688                        final InstallArgs args = state.getInstallArgs();
1689                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1690
1691                        Slog.i(TAG, "Verification timed out for " + originUri);
1692                        mPendingVerification.remove(verificationId);
1693
1694                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1695
1696                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1697                            Slog.i(TAG, "Continuing with installation of " + originUri);
1698                            state.setVerifierResponse(Binder.getCallingUid(),
1699                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1700                            broadcastPackageVerified(verificationId, originUri,
1701                                    PackageManager.VERIFICATION_ALLOW,
1702                                    state.getInstallArgs().getUser());
1703                            try {
1704                                ret = args.copyApk(mContainerService, true);
1705                            } catch (RemoteException e) {
1706                                Slog.e(TAG, "Could not contact the ContainerService");
1707                            }
1708                        } else {
1709                            broadcastPackageVerified(verificationId, originUri,
1710                                    PackageManager.VERIFICATION_REJECT,
1711                                    state.getInstallArgs().getUser());
1712                        }
1713
1714                        Trace.asyncTraceEnd(
1715                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1716
1717                        processPendingInstall(args, ret);
1718                        mHandler.sendEmptyMessage(MCS_UNBIND);
1719                    }
1720                    break;
1721                }
1722                case PACKAGE_VERIFIED: {
1723                    final int verificationId = msg.arg1;
1724
1725                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1726                    if (state == null) {
1727                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1728                        break;
1729                    }
1730
1731                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1732
1733                    state.setVerifierResponse(response.callerUid, response.code);
1734
1735                    if (state.isVerificationComplete()) {
1736                        mPendingVerification.remove(verificationId);
1737
1738                        final InstallArgs args = state.getInstallArgs();
1739                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1740
1741                        int ret;
1742                        if (state.isInstallAllowed()) {
1743                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1744                            broadcastPackageVerified(verificationId, originUri,
1745                                    response.code, state.getInstallArgs().getUser());
1746                            try {
1747                                ret = args.copyApk(mContainerService, true);
1748                            } catch (RemoteException e) {
1749                                Slog.e(TAG, "Could not contact the ContainerService");
1750                            }
1751                        } else {
1752                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1753                        }
1754
1755                        Trace.asyncTraceEnd(
1756                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1757
1758                        processPendingInstall(args, ret);
1759                        mHandler.sendEmptyMessage(MCS_UNBIND);
1760                    }
1761
1762                    break;
1763                }
1764                case START_INTENT_FILTER_VERIFICATIONS: {
1765                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1766                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1767                            params.replacing, params.pkg);
1768                    break;
1769                }
1770                case INTENT_FILTER_VERIFIED: {
1771                    final int verificationId = msg.arg1;
1772
1773                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1774                            verificationId);
1775                    if (state == null) {
1776                        Slog.w(TAG, "Invalid IntentFilter verification token "
1777                                + verificationId + " received");
1778                        break;
1779                    }
1780
1781                    final int userId = state.getUserId();
1782
1783                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1784                            "Processing IntentFilter verification with token:"
1785                            + verificationId + " and userId:" + userId);
1786
1787                    final IntentFilterVerificationResponse response =
1788                            (IntentFilterVerificationResponse) msg.obj;
1789
1790                    state.setVerifierResponse(response.callerUid, response.code);
1791
1792                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1793                            "IntentFilter verification with token:" + verificationId
1794                            + " and userId:" + userId
1795                            + " is settings verifier response with response code:"
1796                            + response.code);
1797
1798                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1799                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1800                                + response.getFailedDomainsString());
1801                    }
1802
1803                    if (state.isVerificationComplete()) {
1804                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1805                    } else {
1806                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1807                                "IntentFilter verification with token:" + verificationId
1808                                + " was not said to be complete");
1809                    }
1810
1811                    break;
1812                }
1813            }
1814        }
1815    }
1816
1817    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1818            boolean killApp, String[] grantedPermissions,
1819            boolean launchedForRestore, String installerPackage,
1820            IPackageInstallObserver2 installObserver) {
1821        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1822            // Send the removed broadcasts
1823            if (res.removedInfo != null) {
1824                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1825            }
1826
1827            // Now that we successfully installed the package, grant runtime
1828            // permissions if requested before broadcasting the install.
1829            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1830                    >= Build.VERSION_CODES.M) {
1831                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1832            }
1833
1834            final boolean update = res.removedInfo != null
1835                    && res.removedInfo.removedPackage != null;
1836
1837            // If this is the first time we have child packages for a disabled privileged
1838            // app that had no children, we grant requested runtime permissions to the new
1839            // children if the parent on the system image had them already granted.
1840            if (res.pkg.parentPackage != null) {
1841                synchronized (mPackages) {
1842                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1843                }
1844            }
1845
1846            synchronized (mPackages) {
1847                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1848            }
1849
1850            final String packageName = res.pkg.applicationInfo.packageName;
1851            Bundle extras = new Bundle(1);
1852            extras.putInt(Intent.EXTRA_UID, res.uid);
1853
1854            // Determine the set of users who are adding this package for
1855            // the first time vs. those who are seeing an update.
1856            int[] firstUsers = EMPTY_INT_ARRAY;
1857            int[] updateUsers = EMPTY_INT_ARRAY;
1858            if (res.origUsers == null || res.origUsers.length == 0) {
1859                firstUsers = res.newUsers;
1860            } else {
1861                for (int newUser : res.newUsers) {
1862                    boolean isNew = true;
1863                    for (int origUser : res.origUsers) {
1864                        if (origUser == newUser) {
1865                            isNew = false;
1866                            break;
1867                        }
1868                    }
1869                    if (isNew) {
1870                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1871                    } else {
1872                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1873                    }
1874                }
1875            }
1876
1877            // Send installed broadcasts if the install/update is not ephemeral
1878            if (!isEphemeral(res.pkg)) {
1879                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1880
1881                // Send added for users that see the package for the first time
1882                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1883                        extras, 0 /*flags*/, null /*targetPackage*/,
1884                        null /*finishedReceiver*/, firstUsers);
1885
1886                // Send added for users that don't see the package for the first time
1887                if (update) {
1888                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1889                }
1890                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1891                        extras, 0 /*flags*/, null /*targetPackage*/,
1892                        null /*finishedReceiver*/, updateUsers);
1893
1894                // Send replaced for users that don't see the package for the first time
1895                if (update) {
1896                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1897                            packageName, extras, 0 /*flags*/,
1898                            null /*targetPackage*/, null /*finishedReceiver*/,
1899                            updateUsers);
1900                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1901                            null /*package*/, null /*extras*/, 0 /*flags*/,
1902                            packageName /*targetPackage*/,
1903                            null /*finishedReceiver*/, updateUsers);
1904                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1905                    // First-install and we did a restore, so we're responsible for the
1906                    // first-launch broadcast.
1907                    if (DEBUG_BACKUP) {
1908                        Slog.i(TAG, "Post-restore of " + packageName
1909                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
1910                    }
1911                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
1912                }
1913
1914                // Send broadcast package appeared if forward locked/external for all users
1915                // treat asec-hosted packages like removable media on upgrade
1916                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1917                    if (DEBUG_INSTALL) {
1918                        Slog.i(TAG, "upgrading pkg " + res.pkg
1919                                + " is ASEC-hosted -> AVAILABLE");
1920                    }
1921                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1922                    ArrayList<String> pkgList = new ArrayList<>(1);
1923                    pkgList.add(packageName);
1924                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1925                }
1926            }
1927
1928            // Work that needs to happen on first install within each user
1929            if (firstUsers != null && firstUsers.length > 0) {
1930                synchronized (mPackages) {
1931                    for (int userId : firstUsers) {
1932                        // If this app is a browser and it's newly-installed for some
1933                        // users, clear any default-browser state in those users. The
1934                        // app's nature doesn't depend on the user, so we can just check
1935                        // its browser nature in any user and generalize.
1936                        if (packageIsBrowser(packageName, userId)) {
1937                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1938                        }
1939
1940                        // We may also need to apply pending (restored) runtime
1941                        // permission grants within these users.
1942                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1943                    }
1944                }
1945            }
1946
1947            // Log current value of "unknown sources" setting
1948            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1949                    getUnknownSourcesSettings());
1950
1951            // Force a gc to clear up things
1952            Runtime.getRuntime().gc();
1953
1954            // Remove the replaced package's older resources safely now
1955            // We delete after a gc for applications  on sdcard.
1956            if (res.removedInfo != null && res.removedInfo.args != null) {
1957                synchronized (mInstallLock) {
1958                    res.removedInfo.args.doPostDeleteLI(true);
1959                }
1960            }
1961        }
1962
1963        // If someone is watching installs - notify them
1964        if (installObserver != null) {
1965            try {
1966                Bundle extras = extrasForInstallResult(res);
1967                installObserver.onPackageInstalled(res.name, res.returnCode,
1968                        res.returnMsg, extras);
1969            } catch (RemoteException e) {
1970                Slog.i(TAG, "Observer no longer exists.");
1971            }
1972        }
1973    }
1974
1975    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1976            PackageParser.Package pkg) {
1977        if (pkg.parentPackage == null) {
1978            return;
1979        }
1980        if (pkg.requestedPermissions == null) {
1981            return;
1982        }
1983        final PackageSetting disabledSysParentPs = mSettings
1984                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1985        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1986                || !disabledSysParentPs.isPrivileged()
1987                || (disabledSysParentPs.childPackageNames != null
1988                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1989            return;
1990        }
1991        final int[] allUserIds = sUserManager.getUserIds();
1992        final int permCount = pkg.requestedPermissions.size();
1993        for (int i = 0; i < permCount; i++) {
1994            String permission = pkg.requestedPermissions.get(i);
1995            BasePermission bp = mSettings.mPermissions.get(permission);
1996            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1997                continue;
1998            }
1999            for (int userId : allUserIds) {
2000                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2001                        permission, userId)) {
2002                    grantRuntimePermission(pkg.packageName, permission, userId);
2003                }
2004            }
2005        }
2006    }
2007
2008    private StorageEventListener mStorageListener = new StorageEventListener() {
2009        @Override
2010        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2011            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2012                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2013                    final String volumeUuid = vol.getFsUuid();
2014
2015                    // Clean up any users or apps that were removed or recreated
2016                    // while this volume was missing
2017                    reconcileUsers(volumeUuid);
2018                    reconcileApps(volumeUuid);
2019
2020                    // Clean up any install sessions that expired or were
2021                    // cancelled while this volume was missing
2022                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2023
2024                    loadPrivatePackages(vol);
2025
2026                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2027                    unloadPrivatePackages(vol);
2028                }
2029            }
2030
2031            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2032                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2033                    updateExternalMediaStatus(true, false);
2034                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2035                    updateExternalMediaStatus(false, false);
2036                }
2037            }
2038        }
2039
2040        @Override
2041        public void onVolumeForgotten(String fsUuid) {
2042            if (TextUtils.isEmpty(fsUuid)) {
2043                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2044                return;
2045            }
2046
2047            // Remove any apps installed on the forgotten volume
2048            synchronized (mPackages) {
2049                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2050                for (PackageSetting ps : packages) {
2051                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2052                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
2053                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2054                }
2055
2056                mSettings.onVolumeForgotten(fsUuid);
2057                mSettings.writeLPr();
2058            }
2059        }
2060    };
2061
2062    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2063            String[] grantedPermissions) {
2064        for (int userId : userIds) {
2065            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2066        }
2067
2068        // We could have touched GID membership, so flush out packages.list
2069        synchronized (mPackages) {
2070            mSettings.writePackageListLPr();
2071        }
2072    }
2073
2074    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2075            String[] grantedPermissions) {
2076        SettingBase sb = (SettingBase) pkg.mExtras;
2077        if (sb == null) {
2078            return;
2079        }
2080
2081        PermissionsState permissionsState = sb.getPermissionsState();
2082
2083        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2084                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2085
2086        for (String permission : pkg.requestedPermissions) {
2087            final BasePermission bp;
2088            synchronized (mPackages) {
2089                bp = mSettings.mPermissions.get(permission);
2090            }
2091            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2092                    && (grantedPermissions == null
2093                           || ArrayUtils.contains(grantedPermissions, permission))) {
2094                final int flags = permissionsState.getPermissionFlags(permission, userId);
2095                // Installer cannot change immutable permissions.
2096                if ((flags & immutableFlags) == 0) {
2097                    grantRuntimePermission(pkg.packageName, permission, userId);
2098                }
2099            }
2100        }
2101    }
2102
2103    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2104        Bundle extras = null;
2105        switch (res.returnCode) {
2106            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2107                extras = new Bundle();
2108                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2109                        res.origPermission);
2110                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2111                        res.origPackage);
2112                break;
2113            }
2114            case PackageManager.INSTALL_SUCCEEDED: {
2115                extras = new Bundle();
2116                extras.putBoolean(Intent.EXTRA_REPLACING,
2117                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2118                break;
2119            }
2120        }
2121        return extras;
2122    }
2123
2124    void scheduleWriteSettingsLocked() {
2125        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2126            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2127        }
2128    }
2129
2130    void scheduleWritePackageListLocked(int userId) {
2131        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2132            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2133            msg.arg1 = userId;
2134            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2135        }
2136    }
2137
2138    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2139        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2140        scheduleWritePackageRestrictionsLocked(userId);
2141    }
2142
2143    void scheduleWritePackageRestrictionsLocked(int userId) {
2144        final int[] userIds = (userId == UserHandle.USER_ALL)
2145                ? sUserManager.getUserIds() : new int[]{userId};
2146        for (int nextUserId : userIds) {
2147            if (!sUserManager.exists(nextUserId)) return;
2148            mDirtyUsers.add(nextUserId);
2149            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2150                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2151            }
2152        }
2153    }
2154
2155    public static PackageManagerService main(Context context, Installer installer,
2156            boolean factoryTest, boolean onlyCore) {
2157        // Self-check for initial settings.
2158        PackageManagerServiceCompilerMapping.checkProperties();
2159
2160        PackageManagerService m = new PackageManagerService(context, installer,
2161                factoryTest, onlyCore);
2162        m.enableSystemUserPackages();
2163        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
2164        // disabled after already being started.
2165        CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m,
2166                UserHandle.USER_SYSTEM);
2167        ServiceManager.addService("package", m);
2168        return m;
2169    }
2170
2171    private void enableSystemUserPackages() {
2172        if (!UserManager.isSplitSystemUser()) {
2173            return;
2174        }
2175        // For system user, enable apps based on the following conditions:
2176        // - app is whitelisted or belong to one of these groups:
2177        //   -- system app which has no launcher icons
2178        //   -- system app which has INTERACT_ACROSS_USERS permission
2179        //   -- system IME app
2180        // - app is not in the blacklist
2181        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2182        Set<String> enableApps = new ArraySet<>();
2183        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2184                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2185                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2186        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2187        enableApps.addAll(wlApps);
2188        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2189                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2190        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2191        enableApps.removeAll(blApps);
2192        Log.i(TAG, "Applications installed for system user: " + enableApps);
2193        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2194                UserHandle.SYSTEM);
2195        final int allAppsSize = allAps.size();
2196        synchronized (mPackages) {
2197            for (int i = 0; i < allAppsSize; i++) {
2198                String pName = allAps.get(i);
2199                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2200                // Should not happen, but we shouldn't be failing if it does
2201                if (pkgSetting == null) {
2202                    continue;
2203                }
2204                boolean install = enableApps.contains(pName);
2205                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2206                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2207                            + " for system user");
2208                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2209                }
2210            }
2211        }
2212    }
2213
2214    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2215        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2216                Context.DISPLAY_SERVICE);
2217        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2218    }
2219
2220    public PackageManagerService(Context context, Installer installer,
2221            boolean factoryTest, boolean onlyCore) {
2222        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2223                SystemClock.uptimeMillis());
2224
2225        if (mSdkVersion <= 0) {
2226            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2227        }
2228
2229        mContext = context;
2230        mFactoryTest = factoryTest;
2231        mOnlyCore = onlyCore;
2232        mMetrics = new DisplayMetrics();
2233        mSettings = new Settings(mPackages);
2234        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2235                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2236        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2237                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2238        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2239                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2240        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2241                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2242        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2243                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2244        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2245                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2246
2247        String separateProcesses = SystemProperties.get("debug.separate_processes");
2248        if (separateProcesses != null && separateProcesses.length() > 0) {
2249            if ("*".equals(separateProcesses)) {
2250                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2251                mSeparateProcesses = null;
2252                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2253            } else {
2254                mDefParseFlags = 0;
2255                mSeparateProcesses = separateProcesses.split(",");
2256                Slog.w(TAG, "Running with debug.separate_processes: "
2257                        + separateProcesses);
2258            }
2259        } else {
2260            mDefParseFlags = 0;
2261            mSeparateProcesses = null;
2262        }
2263
2264        mInstaller = installer;
2265        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2266                "*dexopt*");
2267        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2268
2269        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2270                FgThread.get().getLooper());
2271
2272        getDefaultDisplayMetrics(context, mMetrics);
2273
2274        SystemConfig systemConfig = SystemConfig.getInstance();
2275        mGlobalGids = systemConfig.getGlobalGids();
2276        mSystemPermissions = systemConfig.getSystemPermissions();
2277        mAvailableFeatures = systemConfig.getAvailableFeatures();
2278
2279        synchronized (mInstallLock) {
2280        // writer
2281        synchronized (mPackages) {
2282            mHandlerThread = new ServiceThread(TAG,
2283                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2284            mHandlerThread.start();
2285            mHandler = new PackageHandler(mHandlerThread.getLooper());
2286            mProcessLoggingHandler = new ProcessLoggingHandler();
2287            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2288
2289            File dataDir = Environment.getDataDirectory();
2290            mAppInstallDir = new File(dataDir, "app");
2291            mAppLib32InstallDir = new File(dataDir, "app-lib");
2292            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2293            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2294            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2295
2296            sUserManager = new UserManagerService(context, this, mPackages);
2297
2298            // Propagate permission configuration in to package manager.
2299            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2300                    = systemConfig.getPermissions();
2301            for (int i=0; i<permConfig.size(); i++) {
2302                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2303                BasePermission bp = mSettings.mPermissions.get(perm.name);
2304                if (bp == null) {
2305                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2306                    mSettings.mPermissions.put(perm.name, bp);
2307                }
2308                if (perm.gids != null) {
2309                    bp.setGids(perm.gids, perm.perUser);
2310                }
2311            }
2312
2313            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2314            for (int i=0; i<libConfig.size(); i++) {
2315                mSharedLibraries.put(libConfig.keyAt(i),
2316                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2317            }
2318
2319            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2320
2321            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2322
2323            String customResolverActivity = Resources.getSystem().getString(
2324                    R.string.config_customResolverActivity);
2325            if (TextUtils.isEmpty(customResolverActivity)) {
2326                customResolverActivity = null;
2327            } else {
2328                mCustomResolverComponentName = ComponentName.unflattenFromString(
2329                        customResolverActivity);
2330            }
2331
2332            long startTime = SystemClock.uptimeMillis();
2333
2334            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2335                    startTime);
2336
2337            // Set flag to monitor and not change apk file paths when
2338            // scanning install directories.
2339            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2340
2341            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2342            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2343
2344            if (bootClassPath == null) {
2345                Slog.w(TAG, "No BOOTCLASSPATH found!");
2346            }
2347
2348            if (systemServerClassPath == null) {
2349                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2350            }
2351
2352            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2353            final String[] dexCodeInstructionSets =
2354                    getDexCodeInstructionSets(
2355                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2356
2357            /**
2358             * Ensure all external libraries have had dexopt run on them.
2359             */
2360            if (mSharedLibraries.size() > 0) {
2361                // NOTE: For now, we're compiling these system "shared libraries"
2362                // (and framework jars) into all available architectures. It's possible
2363                // to compile them only when we come across an app that uses them (there's
2364                // already logic for that in scanPackageLI) but that adds some complexity.
2365                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2366                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2367                        final String lib = libEntry.path;
2368                        if (lib == null) {
2369                            continue;
2370                        }
2371
2372                        try {
2373                            // Shared libraries do not have profiles so we perform a full
2374                            // AOT compilation (if needed).
2375                            int dexoptNeeded = DexFile.getDexOptNeeded(
2376                                    lib, dexCodeInstructionSet,
2377                                    getCompilerFilterForReason(REASON_SHARED_APK),
2378                                    false /* newProfile */);
2379                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2380                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2381                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2382                                        getCompilerFilterForReason(REASON_SHARED_APK),
2383                                        StorageManager.UUID_PRIVATE_INTERNAL,
2384                                        SKIP_SHARED_LIBRARY_CHECK);
2385                            }
2386                        } catch (FileNotFoundException e) {
2387                            Slog.w(TAG, "Library not found: " + lib);
2388                        } catch (IOException | InstallerException e) {
2389                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2390                                    + e.getMessage());
2391                        }
2392                    }
2393                }
2394            }
2395
2396            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2397
2398            final VersionInfo ver = mSettings.getInternalVersion();
2399            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2400
2401            // when upgrading from pre-M, promote system app permissions from install to runtime
2402            mPromoteSystemApps =
2403                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2404
2405            // When upgrading from pre-N, we need to handle package extraction like first boot,
2406            // as there is no profiling data available.
2407            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2408
2409            // save off the names of pre-existing system packages prior to scanning; we don't
2410            // want to automatically grant runtime permissions for new system apps
2411            if (mPromoteSystemApps) {
2412                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2413                while (pkgSettingIter.hasNext()) {
2414                    PackageSetting ps = pkgSettingIter.next();
2415                    if (isSystemApp(ps)) {
2416                        mExistingSystemPackages.add(ps.name);
2417                    }
2418                }
2419            }
2420
2421            // Collect vendor overlay packages.
2422            // (Do this before scanning any apps.)
2423            // For security and version matching reason, only consider
2424            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2425            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2426            scanDirTracedLI(vendorOverlayDir, mDefParseFlags
2427                    | PackageParser.PARSE_IS_SYSTEM
2428                    | PackageParser.PARSE_IS_SYSTEM_DIR
2429                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2430
2431            // Find base frameworks (resource packages without code).
2432            scanDirTracedLI(frameworkDir, mDefParseFlags
2433                    | PackageParser.PARSE_IS_SYSTEM
2434                    | PackageParser.PARSE_IS_SYSTEM_DIR
2435                    | PackageParser.PARSE_IS_PRIVILEGED,
2436                    scanFlags | SCAN_NO_DEX, 0);
2437
2438            // Collected privileged system packages.
2439            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2440            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2441                    | PackageParser.PARSE_IS_SYSTEM
2442                    | PackageParser.PARSE_IS_SYSTEM_DIR
2443                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2444
2445            // Collect ordinary system packages.
2446            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2447            scanDirTracedLI(systemAppDir, mDefParseFlags
2448                    | PackageParser.PARSE_IS_SYSTEM
2449                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2450
2451            // Collect all vendor packages.
2452            File vendorAppDir = new File("/vendor/app");
2453            try {
2454                vendorAppDir = vendorAppDir.getCanonicalFile();
2455            } catch (IOException e) {
2456                // failed to look up canonical path, continue with original one
2457            }
2458            scanDirTracedLI(vendorAppDir, mDefParseFlags
2459                    | PackageParser.PARSE_IS_SYSTEM
2460                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2461
2462            // Collect all OEM packages.
2463            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2464            scanDirTracedLI(oemAppDir, mDefParseFlags
2465                    | PackageParser.PARSE_IS_SYSTEM
2466                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2467
2468            // Prune any system packages that no longer exist.
2469            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2470            if (!mOnlyCore) {
2471                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2472                while (psit.hasNext()) {
2473                    PackageSetting ps = psit.next();
2474
2475                    /*
2476                     * If this is not a system app, it can't be a
2477                     * disable system app.
2478                     */
2479                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2480                        continue;
2481                    }
2482
2483                    /*
2484                     * If the package is scanned, it's not erased.
2485                     */
2486                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2487                    if (scannedPkg != null) {
2488                        /*
2489                         * If the system app is both scanned and in the
2490                         * disabled packages list, then it must have been
2491                         * added via OTA. Remove it from the currently
2492                         * scanned package so the previously user-installed
2493                         * application can be scanned.
2494                         */
2495                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2496                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2497                                    + ps.name + "; removing system app.  Last known codePath="
2498                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2499                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2500                                    + scannedPkg.mVersionCode);
2501                            removePackageLI(scannedPkg, true);
2502                            mExpectingBetter.put(ps.name, ps.codePath);
2503                        }
2504
2505                        continue;
2506                    }
2507
2508                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2509                        psit.remove();
2510                        logCriticalInfo(Log.WARN, "System package " + ps.name
2511                                + " no longer exists; it's data will be wiped");
2512                        // Actual deletion of code and data will be handled by later
2513                        // reconciliation step
2514                    } else {
2515                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2516                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2517                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2518                        }
2519                    }
2520                }
2521            }
2522
2523            //look for any incomplete package installations
2524            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2525            for (int i = 0; i < deletePkgsList.size(); i++) {
2526                // Actual deletion of code and data will be handled by later
2527                // reconciliation step
2528                final String packageName = deletePkgsList.get(i).name;
2529                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2530                synchronized (mPackages) {
2531                    mSettings.removePackageLPw(packageName);
2532                }
2533            }
2534
2535            //delete tmp files
2536            deleteTempPackageFiles();
2537
2538            // Remove any shared userIDs that have no associated packages
2539            mSettings.pruneSharedUsersLPw();
2540
2541            if (!mOnlyCore) {
2542                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2543                        SystemClock.uptimeMillis());
2544                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2545
2546                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2547                        | PackageParser.PARSE_FORWARD_LOCK,
2548                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2549
2550                scanDirLI(mEphemeralInstallDir, mDefParseFlags
2551                        | PackageParser.PARSE_IS_EPHEMERAL,
2552                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2553
2554                /**
2555                 * Remove disable package settings for any updated system
2556                 * apps that were removed via an OTA. If they're not a
2557                 * previously-updated app, remove them completely.
2558                 * Otherwise, just revoke their system-level permissions.
2559                 */
2560                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2561                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2562                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2563
2564                    String msg;
2565                    if (deletedPkg == null) {
2566                        msg = "Updated system package " + deletedAppName
2567                                + " no longer exists; it's data will be wiped";
2568                        // Actual deletion of code and data will be handled by later
2569                        // reconciliation step
2570                    } else {
2571                        msg = "Updated system app + " + deletedAppName
2572                                + " no longer present; removing system privileges for "
2573                                + deletedAppName;
2574
2575                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2576
2577                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2578                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2579                    }
2580                    logCriticalInfo(Log.WARN, msg);
2581                }
2582
2583                /**
2584                 * Make sure all system apps that we expected to appear on
2585                 * the userdata partition actually showed up. If they never
2586                 * appeared, crawl back and revive the system version.
2587                 */
2588                for (int i = 0; i < mExpectingBetter.size(); i++) {
2589                    final String packageName = mExpectingBetter.keyAt(i);
2590                    if (!mPackages.containsKey(packageName)) {
2591                        final File scanFile = mExpectingBetter.valueAt(i);
2592
2593                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2594                                + " but never showed up; reverting to system");
2595
2596                        int reparseFlags = mDefParseFlags;
2597                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2598                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2599                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2600                                    | PackageParser.PARSE_IS_PRIVILEGED;
2601                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2602                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2603                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2604                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2605                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2606                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2607                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2608                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2609                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2610                        } else {
2611                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2612                            continue;
2613                        }
2614
2615                        mSettings.enableSystemPackageLPw(packageName);
2616
2617                        try {
2618                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2619                        } catch (PackageManagerException e) {
2620                            Slog.e(TAG, "Failed to parse original system package: "
2621                                    + e.getMessage());
2622                        }
2623                    }
2624                }
2625            }
2626            mExpectingBetter.clear();
2627
2628            // Resolve protected action filters. Only the setup wizard is allowed to
2629            // have a high priority filter for these actions.
2630            mSetupWizardPackage = getSetupWizardPackageName();
2631            if (mProtectedFilters.size() > 0) {
2632                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2633                    Slog.i(TAG, "No setup wizard;"
2634                        + " All protected intents capped to priority 0");
2635                }
2636                for (ActivityIntentInfo filter : mProtectedFilters) {
2637                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2638                        if (DEBUG_FILTERS) {
2639                            Slog.i(TAG, "Found setup wizard;"
2640                                + " allow priority " + filter.getPriority() + ";"
2641                                + " package: " + filter.activity.info.packageName
2642                                + " activity: " + filter.activity.className
2643                                + " priority: " + filter.getPriority());
2644                        }
2645                        // skip setup wizard; allow it to keep the high priority filter
2646                        continue;
2647                    }
2648                    Slog.w(TAG, "Protected action; cap priority to 0;"
2649                            + " package: " + filter.activity.info.packageName
2650                            + " activity: " + filter.activity.className
2651                            + " origPrio: " + filter.getPriority());
2652                    filter.setPriority(0);
2653                }
2654            }
2655            mDeferProtectedFilters = false;
2656            mProtectedFilters.clear();
2657
2658            // Now that we know all of the shared libraries, update all clients to have
2659            // the correct library paths.
2660            updateAllSharedLibrariesLPw();
2661
2662            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2663                // NOTE: We ignore potential failures here during a system scan (like
2664                // the rest of the commands above) because there's precious little we
2665                // can do about it. A settings error is reported, though.
2666                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2667                        false /* boot complete */);
2668            }
2669
2670            // Now that we know all the packages we are keeping,
2671            // read and update their last usage times.
2672            mPackageUsage.readLP();
2673
2674            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2675                    SystemClock.uptimeMillis());
2676            Slog.i(TAG, "Time to scan packages: "
2677                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2678                    + " seconds");
2679
2680            // If the platform SDK has changed since the last time we booted,
2681            // we need to re-grant app permission to catch any new ones that
2682            // appear.  This is really a hack, and means that apps can in some
2683            // cases get permissions that the user didn't initially explicitly
2684            // allow...  it would be nice to have some better way to handle
2685            // this situation.
2686            int updateFlags = UPDATE_PERMISSIONS_ALL;
2687            if (ver.sdkVersion != mSdkVersion) {
2688                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2689                        + mSdkVersion + "; regranting permissions for internal storage");
2690                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2691            }
2692            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2693            ver.sdkVersion = mSdkVersion;
2694
2695            // If this is the first boot or an update from pre-M, and it is a normal
2696            // boot, then we need to initialize the default preferred apps across
2697            // all defined users.
2698            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2699                for (UserInfo user : sUserManager.getUsers(true)) {
2700                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2701                    applyFactoryDefaultBrowserLPw(user.id);
2702                    primeDomainVerificationsLPw(user.id);
2703                }
2704            }
2705
2706            // Prepare storage for system user really early during boot,
2707            // since core system apps like SettingsProvider and SystemUI
2708            // can't wait for user to start
2709            final int storageFlags;
2710            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2711                storageFlags = StorageManager.FLAG_STORAGE_DE;
2712            } else {
2713                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2714            }
2715            reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2716                    storageFlags);
2717
2718            // If this is first boot after an OTA, and a normal boot, then
2719            // we need to clear code cache directories.
2720            // Note that we do *not* clear the application profiles. These remain valid
2721            // across OTAs and are used to drive profile verification (post OTA) and
2722            // profile compilation (without waiting to collect a fresh set of profiles).
2723            if (mIsUpgrade && !onlyCore) {
2724                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2725                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2726                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2727                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2728                        // No apps are running this early, so no need to freeze
2729                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2730                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2731                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2732                    }
2733                }
2734                ver.fingerprint = Build.FINGERPRINT;
2735            }
2736
2737            checkDefaultBrowser();
2738
2739            // clear only after permissions and other defaults have been updated
2740            mExistingSystemPackages.clear();
2741            mPromoteSystemApps = false;
2742
2743            // All the changes are done during package scanning.
2744            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2745
2746            // can downgrade to reader
2747            mSettings.writeLPr();
2748
2749            // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty
2750            // early on (before the package manager declares itself as early) because other
2751            // components in the system server might ask for package contexts for these apps.
2752            //
2753            // Note that "onlyCore" in this context means the system is encrypted or encrypting
2754            // (i.e, that the data partition is unavailable).
2755            if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) {
2756                long start = System.nanoTime();
2757                List<PackageParser.Package> coreApps = new ArrayList<>();
2758                for (PackageParser.Package pkg : mPackages.values()) {
2759                    if (pkg.coreApp) {
2760                        coreApps.add(pkg);
2761                    }
2762                }
2763
2764                int[] stats = performDexOpt(coreApps, false,
2765                        getCompilerFilterForReason(REASON_CORE_APP));
2766
2767                final int elapsedTimeSeconds =
2768                        (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);
2769                MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds);
2770
2771                if (DEBUG_DEXOPT) {
2772                    Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" +
2773                            stats[0] + ", " + stats[1] + ", " + stats[2] + ")");
2774                }
2775
2776
2777                // TODO: Should we log these stats to tron too ?
2778                // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]);
2779                // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]);
2780                // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]);
2781                // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size());
2782            }
2783
2784            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2785                    SystemClock.uptimeMillis());
2786
2787            if (!mOnlyCore) {
2788                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2789                mRequiredInstallerPackage = getRequiredInstallerLPr();
2790                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2791                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2792                        mIntentFilterVerifierComponent);
2793                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2794                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
2795                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2796                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED);
2797            } else {
2798                mRequiredVerifierPackage = null;
2799                mRequiredInstallerPackage = null;
2800                mIntentFilterVerifierComponent = null;
2801                mIntentFilterVerifier = null;
2802                mServicesSystemSharedLibraryPackageName = null;
2803                mSharedSystemSharedLibraryPackageName = null;
2804            }
2805
2806            mInstallerService = new PackageInstallerService(context, this);
2807
2808            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2809            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2810            // both the installer and resolver must be present to enable ephemeral
2811            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2812                if (DEBUG_EPHEMERAL) {
2813                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2814                            + " installer:" + ephemeralInstallerComponent);
2815                }
2816                mEphemeralResolverComponent = ephemeralResolverComponent;
2817                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2818                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2819                mEphemeralResolverConnection =
2820                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2821            } else {
2822                if (DEBUG_EPHEMERAL) {
2823                    final String missingComponent =
2824                            (ephemeralResolverComponent == null)
2825                            ? (ephemeralInstallerComponent == null)
2826                                    ? "resolver and installer"
2827                                    : "resolver"
2828                            : "installer";
2829                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2830                }
2831                mEphemeralResolverComponent = null;
2832                mEphemeralInstallerComponent = null;
2833                mEphemeralResolverConnection = null;
2834            }
2835
2836            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2837        } // synchronized (mPackages)
2838        } // synchronized (mInstallLock)
2839
2840        // Now after opening every single application zip, make sure they
2841        // are all flushed.  Not really needed, but keeps things nice and
2842        // tidy.
2843        Runtime.getRuntime().gc();
2844
2845        // The initial scanning above does many calls into installd while
2846        // holding the mPackages lock, but we're mostly interested in yelling
2847        // once we have a booted system.
2848        mInstaller.setWarnIfHeld(mPackages);
2849
2850        // Expose private service for system components to use.
2851        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2852    }
2853
2854    @Override
2855    public boolean isFirstBoot() {
2856        return !mRestoredSettings;
2857    }
2858
2859    @Override
2860    public boolean isOnlyCoreApps() {
2861        return mOnlyCore;
2862    }
2863
2864    @Override
2865    public boolean isUpgrade() {
2866        return mIsUpgrade;
2867    }
2868
2869    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2870        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2871
2872        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2873                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2874                UserHandle.USER_SYSTEM);
2875        if (matches.size() == 1) {
2876            return matches.get(0).getComponentInfo().packageName;
2877        } else {
2878            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2879            return null;
2880        }
2881    }
2882
2883    private @NonNull String getRequiredSharedLibraryLPr(String libraryName) {
2884        synchronized (mPackages) {
2885            SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName);
2886            if (libraryEntry == null) {
2887                throw new IllegalStateException("Missing required shared library:" + libraryName);
2888            }
2889            return libraryEntry.apk;
2890        }
2891    }
2892
2893    private @NonNull String getRequiredInstallerLPr() {
2894        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2895        intent.addCategory(Intent.CATEGORY_DEFAULT);
2896        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2897
2898        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2899                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2900                UserHandle.USER_SYSTEM);
2901        if (matches.size() == 1) {
2902            ResolveInfo resolveInfo = matches.get(0);
2903            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2904                throw new RuntimeException("The installer must be a privileged app");
2905            }
2906            return matches.get(0).getComponentInfo().packageName;
2907        } else {
2908            throw new RuntimeException("There must be exactly one installer; found " + matches);
2909        }
2910    }
2911
2912    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2913        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2914
2915        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2916                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2917                UserHandle.USER_SYSTEM);
2918        ResolveInfo best = null;
2919        final int N = matches.size();
2920        for (int i = 0; i < N; i++) {
2921            final ResolveInfo cur = matches.get(i);
2922            final String packageName = cur.getComponentInfo().packageName;
2923            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2924                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2925                continue;
2926            }
2927
2928            if (best == null || cur.priority > best.priority) {
2929                best = cur;
2930            }
2931        }
2932
2933        if (best != null) {
2934            return best.getComponentInfo().getComponentName();
2935        } else {
2936            throw new RuntimeException("There must be at least one intent filter verifier");
2937        }
2938    }
2939
2940    private @Nullable ComponentName getEphemeralResolverLPr() {
2941        final String[] packageArray =
2942                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2943        if (packageArray.length == 0) {
2944            if (DEBUG_EPHEMERAL) {
2945                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2946            }
2947            return null;
2948        }
2949
2950        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2951        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2952                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2953                UserHandle.USER_SYSTEM);
2954
2955        final int N = resolvers.size();
2956        if (N == 0) {
2957            if (DEBUG_EPHEMERAL) {
2958                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2959            }
2960            return null;
2961        }
2962
2963        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2964        for (int i = 0; i < N; i++) {
2965            final ResolveInfo info = resolvers.get(i);
2966
2967            if (info.serviceInfo == null) {
2968                continue;
2969            }
2970
2971            final String packageName = info.serviceInfo.packageName;
2972            if (!possiblePackages.contains(packageName)) {
2973                if (DEBUG_EPHEMERAL) {
2974                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2975                            + " pkg: " + packageName + ", info:" + info);
2976                }
2977                continue;
2978            }
2979
2980            if (DEBUG_EPHEMERAL) {
2981                Slog.v(TAG, "Ephemeral resolver found;"
2982                        + " pkg: " + packageName + ", info:" + info);
2983            }
2984            return new ComponentName(packageName, info.serviceInfo.name);
2985        }
2986        if (DEBUG_EPHEMERAL) {
2987            Slog.v(TAG, "Ephemeral resolver NOT found");
2988        }
2989        return null;
2990    }
2991
2992    private @Nullable ComponentName getEphemeralInstallerLPr() {
2993        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2994        intent.addCategory(Intent.CATEGORY_DEFAULT);
2995        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2996
2997        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2998                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2999                UserHandle.USER_SYSTEM);
3000        if (matches.size() == 0) {
3001            return null;
3002        } else if (matches.size() == 1) {
3003            return matches.get(0).getComponentInfo().getComponentName();
3004        } else {
3005            throw new RuntimeException(
3006                    "There must be at most one ephemeral installer; found " + matches);
3007        }
3008    }
3009
3010    private void primeDomainVerificationsLPw(int userId) {
3011        if (DEBUG_DOMAIN_VERIFICATION) {
3012            Slog.d(TAG, "Priming domain verifications in user " + userId);
3013        }
3014
3015        SystemConfig systemConfig = SystemConfig.getInstance();
3016        ArraySet<String> packages = systemConfig.getLinkedApps();
3017        ArraySet<String> domains = new ArraySet<String>();
3018
3019        for (String packageName : packages) {
3020            PackageParser.Package pkg = mPackages.get(packageName);
3021            if (pkg != null) {
3022                if (!pkg.isSystemApp()) {
3023                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3024                    continue;
3025                }
3026
3027                domains.clear();
3028                for (PackageParser.Activity a : pkg.activities) {
3029                    for (ActivityIntentInfo filter : a.intents) {
3030                        if (hasValidDomains(filter)) {
3031                            domains.addAll(filter.getHostsList());
3032                        }
3033                    }
3034                }
3035
3036                if (domains.size() > 0) {
3037                    if (DEBUG_DOMAIN_VERIFICATION) {
3038                        Slog.v(TAG, "      + " + packageName);
3039                    }
3040                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3041                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3042                    // and then 'always' in the per-user state actually used for intent resolution.
3043                    final IntentFilterVerificationInfo ivi;
3044                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
3045                            new ArrayList<String>(domains));
3046                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3047                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3048                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3049                } else {
3050                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3051                            + "' does not handle web links");
3052                }
3053            } else {
3054                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3055            }
3056        }
3057
3058        scheduleWritePackageRestrictionsLocked(userId);
3059        scheduleWriteSettingsLocked();
3060    }
3061
3062    private void applyFactoryDefaultBrowserLPw(int userId) {
3063        // The default browser app's package name is stored in a string resource,
3064        // with a product-specific overlay used for vendor customization.
3065        String browserPkg = mContext.getResources().getString(
3066                com.android.internal.R.string.default_browser);
3067        if (!TextUtils.isEmpty(browserPkg)) {
3068            // non-empty string => required to be a known package
3069            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3070            if (ps == null) {
3071                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3072                browserPkg = null;
3073            } else {
3074                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3075            }
3076        }
3077
3078        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3079        // default.  If there's more than one, just leave everything alone.
3080        if (browserPkg == null) {
3081            calculateDefaultBrowserLPw(userId);
3082        }
3083    }
3084
3085    private void calculateDefaultBrowserLPw(int userId) {
3086        List<String> allBrowsers = resolveAllBrowserApps(userId);
3087        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3088        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3089    }
3090
3091    private List<String> resolveAllBrowserApps(int userId) {
3092        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3093        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3094                PackageManager.MATCH_ALL, userId);
3095
3096        final int count = list.size();
3097        List<String> result = new ArrayList<String>(count);
3098        for (int i=0; i<count; i++) {
3099            ResolveInfo info = list.get(i);
3100            if (info.activityInfo == null
3101                    || !info.handleAllWebDataURI
3102                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3103                    || result.contains(info.activityInfo.packageName)) {
3104                continue;
3105            }
3106            result.add(info.activityInfo.packageName);
3107        }
3108
3109        return result;
3110    }
3111
3112    private boolean packageIsBrowser(String packageName, int userId) {
3113        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3114                PackageManager.MATCH_ALL, userId);
3115        final int N = list.size();
3116        for (int i = 0; i < N; i++) {
3117            ResolveInfo info = list.get(i);
3118            if (packageName.equals(info.activityInfo.packageName)) {
3119                return true;
3120            }
3121        }
3122        return false;
3123    }
3124
3125    private void checkDefaultBrowser() {
3126        final int myUserId = UserHandle.myUserId();
3127        final String packageName = getDefaultBrowserPackageName(myUserId);
3128        if (packageName != null) {
3129            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3130            if (info == null) {
3131                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3132                synchronized (mPackages) {
3133                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3134                }
3135            }
3136        }
3137    }
3138
3139    @Override
3140    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3141            throws RemoteException {
3142        try {
3143            return super.onTransact(code, data, reply, flags);
3144        } catch (RuntimeException e) {
3145            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3146                Slog.wtf(TAG, "Package Manager Crash", e);
3147            }
3148            throw e;
3149        }
3150    }
3151
3152    static int[] appendInts(int[] cur, int[] add) {
3153        if (add == null) return cur;
3154        if (cur == null) return add;
3155        final int N = add.length;
3156        for (int i=0; i<N; i++) {
3157            cur = appendInt(cur, add[i]);
3158        }
3159        return cur;
3160    }
3161
3162    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3163        if (!sUserManager.exists(userId)) return null;
3164        if (ps == null) {
3165            return null;
3166        }
3167        final PackageParser.Package p = ps.pkg;
3168        if (p == null) {
3169            return null;
3170        }
3171
3172        final PermissionsState permissionsState = ps.getPermissionsState();
3173
3174        final int[] gids = permissionsState.computeGids(userId);
3175        final Set<String> permissions = permissionsState.getPermissions(userId);
3176        final PackageUserState state = ps.readUserState(userId);
3177
3178        return PackageParser.generatePackageInfo(p, gids, flags,
3179                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3180    }
3181
3182    @Override
3183    public void checkPackageStartable(String packageName, int userId) {
3184        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3185
3186        synchronized (mPackages) {
3187            final PackageSetting ps = mSettings.mPackages.get(packageName);
3188            if (ps == null) {
3189                throw new SecurityException("Package " + packageName + " was not found!");
3190            }
3191
3192            if (!ps.getInstalled(userId)) {
3193                throw new SecurityException(
3194                        "Package " + packageName + " was not installed for user " + userId + "!");
3195            }
3196
3197            if (mSafeMode && !ps.isSystem()) {
3198                throw new SecurityException("Package " + packageName + " not a system app!");
3199            }
3200
3201            if (mFrozenPackages.contains(packageName)) {
3202                throw new SecurityException("Package " + packageName + " is currently frozen!");
3203            }
3204
3205            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3206                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3207                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3208            }
3209        }
3210    }
3211
3212    @Override
3213    public boolean isPackageAvailable(String packageName, int userId) {
3214        if (!sUserManager.exists(userId)) return false;
3215        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3216                false /* requireFullPermission */, false /* checkShell */, "is package available");
3217        synchronized (mPackages) {
3218            PackageParser.Package p = mPackages.get(packageName);
3219            if (p != null) {
3220                final PackageSetting ps = (PackageSetting) p.mExtras;
3221                if (ps != null) {
3222                    final PackageUserState state = ps.readUserState(userId);
3223                    if (state != null) {
3224                        return PackageParser.isAvailable(state);
3225                    }
3226                }
3227            }
3228        }
3229        return false;
3230    }
3231
3232    @Override
3233    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3234        if (!sUserManager.exists(userId)) return null;
3235        flags = updateFlagsForPackage(flags, userId, packageName);
3236        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3237                false /* requireFullPermission */, false /* checkShell */, "get package info");
3238        // reader
3239        synchronized (mPackages) {
3240            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3241            PackageParser.Package p = null;
3242            if (matchFactoryOnly) {
3243                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3244                if (ps != null) {
3245                    return generatePackageInfo(ps, flags, userId);
3246                }
3247            }
3248            if (p == null) {
3249                p = mPackages.get(packageName);
3250                if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3251                    return null;
3252                }
3253            }
3254            if (DEBUG_PACKAGE_INFO)
3255                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3256            if (p != null) {
3257                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3258            }
3259            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3260                final PackageSetting ps = mSettings.mPackages.get(packageName);
3261                return generatePackageInfo(ps, flags, userId);
3262            }
3263        }
3264        return null;
3265    }
3266
3267    @Override
3268    public String[] currentToCanonicalPackageNames(String[] names) {
3269        String[] out = new String[names.length];
3270        // reader
3271        synchronized (mPackages) {
3272            for (int i=names.length-1; i>=0; i--) {
3273                PackageSetting ps = mSettings.mPackages.get(names[i]);
3274                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3275            }
3276        }
3277        return out;
3278    }
3279
3280    @Override
3281    public String[] canonicalToCurrentPackageNames(String[] names) {
3282        String[] out = new String[names.length];
3283        // reader
3284        synchronized (mPackages) {
3285            for (int i=names.length-1; i>=0; i--) {
3286                String cur = mSettings.mRenamedPackages.get(names[i]);
3287                out[i] = cur != null ? cur : names[i];
3288            }
3289        }
3290        return out;
3291    }
3292
3293    @Override
3294    public int getPackageUid(String packageName, int flags, int userId) {
3295        if (!sUserManager.exists(userId)) return -1;
3296        flags = updateFlagsForPackage(flags, userId, packageName);
3297        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3298                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3299
3300        // reader
3301        synchronized (mPackages) {
3302            final PackageParser.Package p = mPackages.get(packageName);
3303            if (p != null && p.isMatch(flags)) {
3304                return UserHandle.getUid(userId, p.applicationInfo.uid);
3305            }
3306            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3307                final PackageSetting ps = mSettings.mPackages.get(packageName);
3308                if (ps != null && ps.isMatch(flags)) {
3309                    return UserHandle.getUid(userId, ps.appId);
3310                }
3311            }
3312        }
3313
3314        return -1;
3315    }
3316
3317    @Override
3318    public int[] getPackageGids(String packageName, int flags, int userId) {
3319        if (!sUserManager.exists(userId)) return null;
3320        flags = updateFlagsForPackage(flags, userId, packageName);
3321        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3322                false /* requireFullPermission */, false /* checkShell */,
3323                "getPackageGids");
3324
3325        // reader
3326        synchronized (mPackages) {
3327            final PackageParser.Package p = mPackages.get(packageName);
3328            if (p != null && p.isMatch(flags)) {
3329                PackageSetting ps = (PackageSetting) p.mExtras;
3330                return ps.getPermissionsState().computeGids(userId);
3331            }
3332            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3333                final PackageSetting ps = mSettings.mPackages.get(packageName);
3334                if (ps != null && ps.isMatch(flags)) {
3335                    return ps.getPermissionsState().computeGids(userId);
3336                }
3337            }
3338        }
3339
3340        return null;
3341    }
3342
3343    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3344        if (bp.perm != null) {
3345            return PackageParser.generatePermissionInfo(bp.perm, flags);
3346        }
3347        PermissionInfo pi = new PermissionInfo();
3348        pi.name = bp.name;
3349        pi.packageName = bp.sourcePackage;
3350        pi.nonLocalizedLabel = bp.name;
3351        pi.protectionLevel = bp.protectionLevel;
3352        return pi;
3353    }
3354
3355    @Override
3356    public PermissionInfo getPermissionInfo(String name, int flags) {
3357        // reader
3358        synchronized (mPackages) {
3359            final BasePermission p = mSettings.mPermissions.get(name);
3360            if (p != null) {
3361                return generatePermissionInfo(p, flags);
3362            }
3363            return null;
3364        }
3365    }
3366
3367    @Override
3368    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3369            int flags) {
3370        // reader
3371        synchronized (mPackages) {
3372            if (group != null && !mPermissionGroups.containsKey(group)) {
3373                // This is thrown as NameNotFoundException
3374                return null;
3375            }
3376
3377            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3378            for (BasePermission p : mSettings.mPermissions.values()) {
3379                if (group == null) {
3380                    if (p.perm == null || p.perm.info.group == null) {
3381                        out.add(generatePermissionInfo(p, flags));
3382                    }
3383                } else {
3384                    if (p.perm != null && group.equals(p.perm.info.group)) {
3385                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3386                    }
3387                }
3388            }
3389            return new ParceledListSlice<>(out);
3390        }
3391    }
3392
3393    @Override
3394    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3395        // reader
3396        synchronized (mPackages) {
3397            return PackageParser.generatePermissionGroupInfo(
3398                    mPermissionGroups.get(name), flags);
3399        }
3400    }
3401
3402    @Override
3403    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3404        // reader
3405        synchronized (mPackages) {
3406            final int N = mPermissionGroups.size();
3407            ArrayList<PermissionGroupInfo> out
3408                    = new ArrayList<PermissionGroupInfo>(N);
3409            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3410                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3411            }
3412            return new ParceledListSlice<>(out);
3413        }
3414    }
3415
3416    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3417            int userId) {
3418        if (!sUserManager.exists(userId)) return null;
3419        PackageSetting ps = mSettings.mPackages.get(packageName);
3420        if (ps != null) {
3421            if (ps.pkg == null) {
3422                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3423                if (pInfo != null) {
3424                    return pInfo.applicationInfo;
3425                }
3426                return null;
3427            }
3428            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3429                    ps.readUserState(userId), userId);
3430        }
3431        return null;
3432    }
3433
3434    @Override
3435    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3436        if (!sUserManager.exists(userId)) return null;
3437        flags = updateFlagsForApplication(flags, userId, packageName);
3438        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3439                false /* requireFullPermission */, false /* checkShell */, "get application info");
3440        // writer
3441        synchronized (mPackages) {
3442            PackageParser.Package p = mPackages.get(packageName);
3443            if (DEBUG_PACKAGE_INFO) Log.v(
3444                    TAG, "getApplicationInfo " + packageName
3445                    + ": " + p);
3446            if (p != null) {
3447                PackageSetting ps = mSettings.mPackages.get(packageName);
3448                if (ps == null) return null;
3449                // Note: isEnabledLP() does not apply here - always return info
3450                return PackageParser.generateApplicationInfo(
3451                        p, flags, ps.readUserState(userId), userId);
3452            }
3453            if ("android".equals(packageName)||"system".equals(packageName)) {
3454                return mAndroidApplication;
3455            }
3456            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3457                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3458            }
3459        }
3460        return null;
3461    }
3462
3463    @Override
3464    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3465            final IPackageDataObserver observer) {
3466        mContext.enforceCallingOrSelfPermission(
3467                android.Manifest.permission.CLEAR_APP_CACHE, null);
3468        // Queue up an async operation since clearing cache may take a little while.
3469        mHandler.post(new Runnable() {
3470            public void run() {
3471                mHandler.removeCallbacks(this);
3472                boolean success = true;
3473                synchronized (mInstallLock) {
3474                    try {
3475                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3476                    } catch (InstallerException e) {
3477                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3478                        success = false;
3479                    }
3480                }
3481                if (observer != null) {
3482                    try {
3483                        observer.onRemoveCompleted(null, success);
3484                    } catch (RemoteException e) {
3485                        Slog.w(TAG, "RemoveException when invoking call back");
3486                    }
3487                }
3488            }
3489        });
3490    }
3491
3492    @Override
3493    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3494            final IntentSender pi) {
3495        mContext.enforceCallingOrSelfPermission(
3496                android.Manifest.permission.CLEAR_APP_CACHE, null);
3497        // Queue up an async operation since clearing cache may take a little while.
3498        mHandler.post(new Runnable() {
3499            public void run() {
3500                mHandler.removeCallbacks(this);
3501                boolean success = true;
3502                synchronized (mInstallLock) {
3503                    try {
3504                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3505                    } catch (InstallerException e) {
3506                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3507                        success = false;
3508                    }
3509                }
3510                if(pi != null) {
3511                    try {
3512                        // Callback via pending intent
3513                        int code = success ? 1 : 0;
3514                        pi.sendIntent(null, code, null,
3515                                null, null);
3516                    } catch (SendIntentException e1) {
3517                        Slog.i(TAG, "Failed to send pending intent");
3518                    }
3519                }
3520            }
3521        });
3522    }
3523
3524    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3525        synchronized (mInstallLock) {
3526            try {
3527                mInstaller.freeCache(volumeUuid, freeStorageSize);
3528            } catch (InstallerException e) {
3529                throw new IOException("Failed to free enough space", e);
3530            }
3531        }
3532    }
3533
3534    /**
3535     * Update given flags based on encryption status of current user.
3536     */
3537    private int updateFlags(int flags, int userId) {
3538        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3539                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3540            // Caller expressed an explicit opinion about what encryption
3541            // aware/unaware components they want to see, so fall through and
3542            // give them what they want
3543        } else {
3544            // Caller expressed no opinion, so match based on user state
3545            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
3546                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3547            } else {
3548                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3549            }
3550        }
3551        return flags;
3552    }
3553
3554    private UserManagerInternal getUserManagerInternal() {
3555        if (mUserManagerInternal == null) {
3556            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3557        }
3558        return mUserManagerInternal;
3559    }
3560
3561    /**
3562     * Update given flags when being used to request {@link PackageInfo}.
3563     */
3564    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3565        boolean triaged = true;
3566        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3567                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3568            // Caller is asking for component details, so they'd better be
3569            // asking for specific encryption matching behavior, or be triaged
3570            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3571                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3572                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3573                triaged = false;
3574            }
3575        }
3576        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3577                | PackageManager.MATCH_SYSTEM_ONLY
3578                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3579            triaged = false;
3580        }
3581        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3582            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3583                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3584        }
3585        return updateFlags(flags, userId);
3586    }
3587
3588    /**
3589     * Update given flags when being used to request {@link ApplicationInfo}.
3590     */
3591    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3592        return updateFlagsForPackage(flags, userId, cookie);
3593    }
3594
3595    /**
3596     * Update given flags when being used to request {@link ComponentInfo}.
3597     */
3598    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3599        if (cookie instanceof Intent) {
3600            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3601                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3602            }
3603        }
3604
3605        boolean triaged = true;
3606        // Caller is asking for component details, so they'd better be
3607        // asking for specific encryption matching behavior, or be triaged
3608        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3609                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3610                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3611            triaged = false;
3612        }
3613        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3614            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3615                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3616        }
3617
3618        return updateFlags(flags, userId);
3619    }
3620
3621    /**
3622     * Update given flags when being used to request {@link ResolveInfo}.
3623     */
3624    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3625        // Safe mode means we shouldn't match any third-party components
3626        if (mSafeMode) {
3627            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3628        }
3629
3630        return updateFlagsForComponent(flags, userId, cookie);
3631    }
3632
3633    @Override
3634    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3635        if (!sUserManager.exists(userId)) return null;
3636        flags = updateFlagsForComponent(flags, userId, component);
3637        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3638                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3639        synchronized (mPackages) {
3640            PackageParser.Activity a = mActivities.mActivities.get(component);
3641
3642            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3643            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3644                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3645                if (ps == null) return null;
3646                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3647                        userId);
3648            }
3649            if (mResolveComponentName.equals(component)) {
3650                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3651                        new PackageUserState(), userId);
3652            }
3653        }
3654        return null;
3655    }
3656
3657    @Override
3658    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3659            String resolvedType) {
3660        synchronized (mPackages) {
3661            if (component.equals(mResolveComponentName)) {
3662                // The resolver supports EVERYTHING!
3663                return true;
3664            }
3665            PackageParser.Activity a = mActivities.mActivities.get(component);
3666            if (a == null) {
3667                return false;
3668            }
3669            for (int i=0; i<a.intents.size(); i++) {
3670                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3671                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3672                    return true;
3673                }
3674            }
3675            return false;
3676        }
3677    }
3678
3679    @Override
3680    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3681        if (!sUserManager.exists(userId)) return null;
3682        flags = updateFlagsForComponent(flags, userId, component);
3683        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3684                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3685        synchronized (mPackages) {
3686            PackageParser.Activity a = mReceivers.mActivities.get(component);
3687            if (DEBUG_PACKAGE_INFO) Log.v(
3688                TAG, "getReceiverInfo " + component + ": " + a);
3689            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3690                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3691                if (ps == null) return null;
3692                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3693                        userId);
3694            }
3695        }
3696        return null;
3697    }
3698
3699    @Override
3700    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3701        if (!sUserManager.exists(userId)) return null;
3702        flags = updateFlagsForComponent(flags, userId, component);
3703        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3704                false /* requireFullPermission */, false /* checkShell */, "get service info");
3705        synchronized (mPackages) {
3706            PackageParser.Service s = mServices.mServices.get(component);
3707            if (DEBUG_PACKAGE_INFO) Log.v(
3708                TAG, "getServiceInfo " + component + ": " + s);
3709            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3710                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3711                if (ps == null) return null;
3712                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3713                        userId);
3714            }
3715        }
3716        return null;
3717    }
3718
3719    @Override
3720    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3721        if (!sUserManager.exists(userId)) return null;
3722        flags = updateFlagsForComponent(flags, userId, component);
3723        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3724                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3725        synchronized (mPackages) {
3726            PackageParser.Provider p = mProviders.mProviders.get(component);
3727            if (DEBUG_PACKAGE_INFO) Log.v(
3728                TAG, "getProviderInfo " + component + ": " + p);
3729            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3730                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3731                if (ps == null) return null;
3732                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3733                        userId);
3734            }
3735        }
3736        return null;
3737    }
3738
3739    @Override
3740    public String[] getSystemSharedLibraryNames() {
3741        Set<String> libSet;
3742        synchronized (mPackages) {
3743            libSet = mSharedLibraries.keySet();
3744            int size = libSet.size();
3745            if (size > 0) {
3746                String[] libs = new String[size];
3747                libSet.toArray(libs);
3748                return libs;
3749            }
3750        }
3751        return null;
3752    }
3753
3754    @Override
3755    public @NonNull String getServicesSystemSharedLibraryPackageName() {
3756        synchronized (mPackages) {
3757            return mServicesSystemSharedLibraryPackageName;
3758        }
3759    }
3760
3761    @Override
3762    public @NonNull String getSharedSystemSharedLibraryPackageName() {
3763        synchronized (mPackages) {
3764            return mSharedSystemSharedLibraryPackageName;
3765        }
3766    }
3767
3768    @Override
3769    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3770        synchronized (mPackages) {
3771            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3772
3773            final FeatureInfo fi = new FeatureInfo();
3774            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3775                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3776            res.add(fi);
3777
3778            return new ParceledListSlice<>(res);
3779        }
3780    }
3781
3782    @Override
3783    public boolean hasSystemFeature(String name, int version) {
3784        synchronized (mPackages) {
3785            final FeatureInfo feat = mAvailableFeatures.get(name);
3786            if (feat == null) {
3787                return false;
3788            } else {
3789                return feat.version >= version;
3790            }
3791        }
3792    }
3793
3794    @Override
3795    public int checkPermission(String permName, String pkgName, int userId) {
3796        if (!sUserManager.exists(userId)) {
3797            return PackageManager.PERMISSION_DENIED;
3798        }
3799
3800        synchronized (mPackages) {
3801            final PackageParser.Package p = mPackages.get(pkgName);
3802            if (p != null && p.mExtras != null) {
3803                final PackageSetting ps = (PackageSetting) p.mExtras;
3804                final PermissionsState permissionsState = ps.getPermissionsState();
3805                if (permissionsState.hasPermission(permName, userId)) {
3806                    return PackageManager.PERMISSION_GRANTED;
3807                }
3808                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3809                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3810                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3811                    return PackageManager.PERMISSION_GRANTED;
3812                }
3813            }
3814        }
3815
3816        return PackageManager.PERMISSION_DENIED;
3817    }
3818
3819    @Override
3820    public int checkUidPermission(String permName, int uid) {
3821        final int userId = UserHandle.getUserId(uid);
3822
3823        if (!sUserManager.exists(userId)) {
3824            return PackageManager.PERMISSION_DENIED;
3825        }
3826
3827        synchronized (mPackages) {
3828            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3829            if (obj != null) {
3830                final SettingBase ps = (SettingBase) obj;
3831                final PermissionsState permissionsState = ps.getPermissionsState();
3832                if (permissionsState.hasPermission(permName, userId)) {
3833                    return PackageManager.PERMISSION_GRANTED;
3834                }
3835                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3836                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3837                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3838                    return PackageManager.PERMISSION_GRANTED;
3839                }
3840            } else {
3841                ArraySet<String> perms = mSystemPermissions.get(uid);
3842                if (perms != null) {
3843                    if (perms.contains(permName)) {
3844                        return PackageManager.PERMISSION_GRANTED;
3845                    }
3846                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3847                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3848                        return PackageManager.PERMISSION_GRANTED;
3849                    }
3850                }
3851            }
3852        }
3853
3854        return PackageManager.PERMISSION_DENIED;
3855    }
3856
3857    @Override
3858    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3859        if (UserHandle.getCallingUserId() != userId) {
3860            mContext.enforceCallingPermission(
3861                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3862                    "isPermissionRevokedByPolicy for user " + userId);
3863        }
3864
3865        if (checkPermission(permission, packageName, userId)
3866                == PackageManager.PERMISSION_GRANTED) {
3867            return false;
3868        }
3869
3870        final long identity = Binder.clearCallingIdentity();
3871        try {
3872            final int flags = getPermissionFlags(permission, packageName, userId);
3873            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3874        } finally {
3875            Binder.restoreCallingIdentity(identity);
3876        }
3877    }
3878
3879    @Override
3880    public String getPermissionControllerPackageName() {
3881        synchronized (mPackages) {
3882            return mRequiredInstallerPackage;
3883        }
3884    }
3885
3886    /**
3887     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3888     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3889     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3890     * @param message the message to log on security exception
3891     */
3892    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3893            boolean checkShell, String message) {
3894        if (userId < 0) {
3895            throw new IllegalArgumentException("Invalid userId " + userId);
3896        }
3897        if (checkShell) {
3898            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3899        }
3900        if (userId == UserHandle.getUserId(callingUid)) return;
3901        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3902            if (requireFullPermission) {
3903                mContext.enforceCallingOrSelfPermission(
3904                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3905            } else {
3906                try {
3907                    mContext.enforceCallingOrSelfPermission(
3908                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3909                } catch (SecurityException se) {
3910                    mContext.enforceCallingOrSelfPermission(
3911                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3912                }
3913            }
3914        }
3915    }
3916
3917    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3918        if (callingUid == Process.SHELL_UID) {
3919            if (userHandle >= 0
3920                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3921                throw new SecurityException("Shell does not have permission to access user "
3922                        + userHandle);
3923            } else if (userHandle < 0) {
3924                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3925                        + Debug.getCallers(3));
3926            }
3927        }
3928    }
3929
3930    private BasePermission findPermissionTreeLP(String permName) {
3931        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3932            if (permName.startsWith(bp.name) &&
3933                    permName.length() > bp.name.length() &&
3934                    permName.charAt(bp.name.length()) == '.') {
3935                return bp;
3936            }
3937        }
3938        return null;
3939    }
3940
3941    private BasePermission checkPermissionTreeLP(String permName) {
3942        if (permName != null) {
3943            BasePermission bp = findPermissionTreeLP(permName);
3944            if (bp != null) {
3945                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3946                    return bp;
3947                }
3948                throw new SecurityException("Calling uid "
3949                        + Binder.getCallingUid()
3950                        + " is not allowed to add to permission tree "
3951                        + bp.name + " owned by uid " + bp.uid);
3952            }
3953        }
3954        throw new SecurityException("No permission tree found for " + permName);
3955    }
3956
3957    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3958        if (s1 == null) {
3959            return s2 == null;
3960        }
3961        if (s2 == null) {
3962            return false;
3963        }
3964        if (s1.getClass() != s2.getClass()) {
3965            return false;
3966        }
3967        return s1.equals(s2);
3968    }
3969
3970    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3971        if (pi1.icon != pi2.icon) return false;
3972        if (pi1.logo != pi2.logo) return false;
3973        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3974        if (!compareStrings(pi1.name, pi2.name)) return false;
3975        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3976        // We'll take care of setting this one.
3977        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3978        // These are not currently stored in settings.
3979        //if (!compareStrings(pi1.group, pi2.group)) return false;
3980        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3981        //if (pi1.labelRes != pi2.labelRes) return false;
3982        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3983        return true;
3984    }
3985
3986    int permissionInfoFootprint(PermissionInfo info) {
3987        int size = info.name.length();
3988        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3989        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3990        return size;
3991    }
3992
3993    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3994        int size = 0;
3995        for (BasePermission perm : mSettings.mPermissions.values()) {
3996            if (perm.uid == tree.uid) {
3997                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3998            }
3999        }
4000        return size;
4001    }
4002
4003    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
4004        // We calculate the max size of permissions defined by this uid and throw
4005        // if that plus the size of 'info' would exceed our stated maximum.
4006        if (tree.uid != Process.SYSTEM_UID) {
4007            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
4008            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
4009                throw new SecurityException("Permission tree size cap exceeded");
4010            }
4011        }
4012    }
4013
4014    boolean addPermissionLocked(PermissionInfo info, boolean async) {
4015        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
4016            throw new SecurityException("Label must be specified in permission");
4017        }
4018        BasePermission tree = checkPermissionTreeLP(info.name);
4019        BasePermission bp = mSettings.mPermissions.get(info.name);
4020        boolean added = bp == null;
4021        boolean changed = true;
4022        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
4023        if (added) {
4024            enforcePermissionCapLocked(info, tree);
4025            bp = new BasePermission(info.name, tree.sourcePackage,
4026                    BasePermission.TYPE_DYNAMIC);
4027        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
4028            throw new SecurityException(
4029                    "Not allowed to modify non-dynamic permission "
4030                    + info.name);
4031        } else {
4032            if (bp.protectionLevel == fixedLevel
4033                    && bp.perm.owner.equals(tree.perm.owner)
4034                    && bp.uid == tree.uid
4035                    && comparePermissionInfos(bp.perm.info, info)) {
4036                changed = false;
4037            }
4038        }
4039        bp.protectionLevel = fixedLevel;
4040        info = new PermissionInfo(info);
4041        info.protectionLevel = fixedLevel;
4042        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
4043        bp.perm.info.packageName = tree.perm.info.packageName;
4044        bp.uid = tree.uid;
4045        if (added) {
4046            mSettings.mPermissions.put(info.name, bp);
4047        }
4048        if (changed) {
4049            if (!async) {
4050                mSettings.writeLPr();
4051            } else {
4052                scheduleWriteSettingsLocked();
4053            }
4054        }
4055        return added;
4056    }
4057
4058    @Override
4059    public boolean addPermission(PermissionInfo info) {
4060        synchronized (mPackages) {
4061            return addPermissionLocked(info, false);
4062        }
4063    }
4064
4065    @Override
4066    public boolean addPermissionAsync(PermissionInfo info) {
4067        synchronized (mPackages) {
4068            return addPermissionLocked(info, true);
4069        }
4070    }
4071
4072    @Override
4073    public void removePermission(String name) {
4074        synchronized (mPackages) {
4075            checkPermissionTreeLP(name);
4076            BasePermission bp = mSettings.mPermissions.get(name);
4077            if (bp != null) {
4078                if (bp.type != BasePermission.TYPE_DYNAMIC) {
4079                    throw new SecurityException(
4080                            "Not allowed to modify non-dynamic permission "
4081                            + name);
4082                }
4083                mSettings.mPermissions.remove(name);
4084                mSettings.writeLPr();
4085            }
4086        }
4087    }
4088
4089    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
4090            BasePermission bp) {
4091        int index = pkg.requestedPermissions.indexOf(bp.name);
4092        if (index == -1) {
4093            throw new SecurityException("Package " + pkg.packageName
4094                    + " has not requested permission " + bp.name);
4095        }
4096        if (!bp.isRuntime() && !bp.isDevelopment()) {
4097            throw new SecurityException("Permission " + bp.name
4098                    + " is not a changeable permission type");
4099        }
4100    }
4101
4102    @Override
4103    public void grantRuntimePermission(String packageName, String name, final int userId) {
4104        if (!sUserManager.exists(userId)) {
4105            Log.e(TAG, "No such user:" + userId);
4106            return;
4107        }
4108
4109        mContext.enforceCallingOrSelfPermission(
4110                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
4111                "grantRuntimePermission");
4112
4113        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4114                true /* requireFullPermission */, true /* checkShell */,
4115                "grantRuntimePermission");
4116
4117        final int uid;
4118        final SettingBase sb;
4119
4120        synchronized (mPackages) {
4121            final PackageParser.Package pkg = mPackages.get(packageName);
4122            if (pkg == null) {
4123                throw new IllegalArgumentException("Unknown package: " + packageName);
4124            }
4125
4126            final BasePermission bp = mSettings.mPermissions.get(name);
4127            if (bp == null) {
4128                throw new IllegalArgumentException("Unknown permission: " + name);
4129            }
4130
4131            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4132
4133            // If a permission review is required for legacy apps we represent
4134            // their permissions as always granted runtime ones since we need
4135            // to keep the review required permission flag per user while an
4136            // install permission's state is shared across all users.
4137            if (Build.PERMISSIONS_REVIEW_REQUIRED
4138                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4139                    && bp.isRuntime()) {
4140                return;
4141            }
4142
4143            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
4144            sb = (SettingBase) pkg.mExtras;
4145            if (sb == null) {
4146                throw new IllegalArgumentException("Unknown package: " + packageName);
4147            }
4148
4149            final PermissionsState permissionsState = sb.getPermissionsState();
4150
4151            final int flags = permissionsState.getPermissionFlags(name, userId);
4152            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4153                throw new SecurityException("Cannot grant system fixed permission "
4154                        + name + " for package " + packageName);
4155            }
4156
4157            if (bp.isDevelopment()) {
4158                // Development permissions must be handled specially, since they are not
4159                // normal runtime permissions.  For now they apply to all users.
4160                if (permissionsState.grantInstallPermission(bp) !=
4161                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4162                    scheduleWriteSettingsLocked();
4163                }
4164                return;
4165            }
4166
4167            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
4168                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
4169                return;
4170            }
4171
4172            final int result = permissionsState.grantRuntimePermission(bp, userId);
4173            switch (result) {
4174                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
4175                    return;
4176                }
4177
4178                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
4179                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4180                    mHandler.post(new Runnable() {
4181                        @Override
4182                        public void run() {
4183                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
4184                        }
4185                    });
4186                }
4187                break;
4188            }
4189
4190            mOnPermissionChangeListeners.onPermissionsChanged(uid);
4191
4192            // Not critical if that is lost - app has to request again.
4193            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4194        }
4195
4196        // Only need to do this if user is initialized. Otherwise it's a new user
4197        // and there are no processes running as the user yet and there's no need
4198        // to make an expensive call to remount processes for the changed permissions.
4199        if (READ_EXTERNAL_STORAGE.equals(name)
4200                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4201            final long token = Binder.clearCallingIdentity();
4202            try {
4203                if (sUserManager.isInitialized(userId)) {
4204                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4205                            MountServiceInternal.class);
4206                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4207                }
4208            } finally {
4209                Binder.restoreCallingIdentity(token);
4210            }
4211        }
4212    }
4213
4214    @Override
4215    public void revokeRuntimePermission(String packageName, String name, int userId) {
4216        if (!sUserManager.exists(userId)) {
4217            Log.e(TAG, "No such user:" + userId);
4218            return;
4219        }
4220
4221        mContext.enforceCallingOrSelfPermission(
4222                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4223                "revokeRuntimePermission");
4224
4225        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4226                true /* requireFullPermission */, true /* checkShell */,
4227                "revokeRuntimePermission");
4228
4229        final int appId;
4230
4231        synchronized (mPackages) {
4232            final PackageParser.Package pkg = mPackages.get(packageName);
4233            if (pkg == null) {
4234                throw new IllegalArgumentException("Unknown package: " + packageName);
4235            }
4236
4237            final BasePermission bp = mSettings.mPermissions.get(name);
4238            if (bp == null) {
4239                throw new IllegalArgumentException("Unknown permission: " + name);
4240            }
4241
4242            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4243
4244            // If a permission review is required for legacy apps we represent
4245            // their permissions as always granted runtime ones since we need
4246            // to keep the review required permission flag per user while an
4247            // install permission's state is shared across all users.
4248            if (Build.PERMISSIONS_REVIEW_REQUIRED
4249                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4250                    && bp.isRuntime()) {
4251                return;
4252            }
4253
4254            SettingBase sb = (SettingBase) pkg.mExtras;
4255            if (sb == null) {
4256                throw new IllegalArgumentException("Unknown package: " + packageName);
4257            }
4258
4259            final PermissionsState permissionsState = sb.getPermissionsState();
4260
4261            final int flags = permissionsState.getPermissionFlags(name, userId);
4262            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4263                throw new SecurityException("Cannot revoke system fixed permission "
4264                        + name + " for package " + packageName);
4265            }
4266
4267            if (bp.isDevelopment()) {
4268                // Development permissions must be handled specially, since they are not
4269                // normal runtime permissions.  For now they apply to all users.
4270                if (permissionsState.revokeInstallPermission(bp) !=
4271                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4272                    scheduleWriteSettingsLocked();
4273                }
4274                return;
4275            }
4276
4277            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4278                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4279                return;
4280            }
4281
4282            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4283
4284            // Critical, after this call app should never have the permission.
4285            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4286
4287            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4288        }
4289
4290        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4291    }
4292
4293    @Override
4294    public void resetRuntimePermissions() {
4295        mContext.enforceCallingOrSelfPermission(
4296                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4297                "revokeRuntimePermission");
4298
4299        int callingUid = Binder.getCallingUid();
4300        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4301            mContext.enforceCallingOrSelfPermission(
4302                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4303                    "resetRuntimePermissions");
4304        }
4305
4306        synchronized (mPackages) {
4307            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4308            for (int userId : UserManagerService.getInstance().getUserIds()) {
4309                final int packageCount = mPackages.size();
4310                for (int i = 0; i < packageCount; i++) {
4311                    PackageParser.Package pkg = mPackages.valueAt(i);
4312                    if (!(pkg.mExtras instanceof PackageSetting)) {
4313                        continue;
4314                    }
4315                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4316                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4317                }
4318            }
4319        }
4320    }
4321
4322    @Override
4323    public int getPermissionFlags(String name, String packageName, int userId) {
4324        if (!sUserManager.exists(userId)) {
4325            return 0;
4326        }
4327
4328        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4329
4330        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4331                true /* requireFullPermission */, false /* checkShell */,
4332                "getPermissionFlags");
4333
4334        synchronized (mPackages) {
4335            final PackageParser.Package pkg = mPackages.get(packageName);
4336            if (pkg == null) {
4337                return 0;
4338            }
4339
4340            final BasePermission bp = mSettings.mPermissions.get(name);
4341            if (bp == null) {
4342                return 0;
4343            }
4344
4345            SettingBase sb = (SettingBase) pkg.mExtras;
4346            if (sb == null) {
4347                return 0;
4348            }
4349
4350            PermissionsState permissionsState = sb.getPermissionsState();
4351            return permissionsState.getPermissionFlags(name, userId);
4352        }
4353    }
4354
4355    @Override
4356    public void updatePermissionFlags(String name, String packageName, int flagMask,
4357            int flagValues, int userId) {
4358        if (!sUserManager.exists(userId)) {
4359            return;
4360        }
4361
4362        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4363
4364        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4365                true /* requireFullPermission */, true /* checkShell */,
4366                "updatePermissionFlags");
4367
4368        // Only the system can change these flags and nothing else.
4369        if (getCallingUid() != Process.SYSTEM_UID) {
4370            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4371            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4372            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4373            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4374            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4375        }
4376
4377        synchronized (mPackages) {
4378            final PackageParser.Package pkg = mPackages.get(packageName);
4379            if (pkg == null) {
4380                throw new IllegalArgumentException("Unknown package: " + packageName);
4381            }
4382
4383            final BasePermission bp = mSettings.mPermissions.get(name);
4384            if (bp == null) {
4385                throw new IllegalArgumentException("Unknown permission: " + name);
4386            }
4387
4388            SettingBase sb = (SettingBase) pkg.mExtras;
4389            if (sb == null) {
4390                throw new IllegalArgumentException("Unknown package: " + packageName);
4391            }
4392
4393            PermissionsState permissionsState = sb.getPermissionsState();
4394
4395            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4396
4397            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4398                // Install and runtime permissions are stored in different places,
4399                // so figure out what permission changed and persist the change.
4400                if (permissionsState.getInstallPermissionState(name) != null) {
4401                    scheduleWriteSettingsLocked();
4402                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4403                        || hadState) {
4404                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4405                }
4406            }
4407        }
4408    }
4409
4410    /**
4411     * Update the permission flags for all packages and runtime permissions of a user in order
4412     * to allow device or profile owner to remove POLICY_FIXED.
4413     */
4414    @Override
4415    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4416        if (!sUserManager.exists(userId)) {
4417            return;
4418        }
4419
4420        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4421
4422        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4423                true /* requireFullPermission */, true /* checkShell */,
4424                "updatePermissionFlagsForAllApps");
4425
4426        // Only the system can change system fixed flags.
4427        if (getCallingUid() != Process.SYSTEM_UID) {
4428            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4429            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4430        }
4431
4432        synchronized (mPackages) {
4433            boolean changed = false;
4434            final int packageCount = mPackages.size();
4435            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4436                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4437                SettingBase sb = (SettingBase) pkg.mExtras;
4438                if (sb == null) {
4439                    continue;
4440                }
4441                PermissionsState permissionsState = sb.getPermissionsState();
4442                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4443                        userId, flagMask, flagValues);
4444            }
4445            if (changed) {
4446                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4447            }
4448        }
4449    }
4450
4451    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4452        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4453                != PackageManager.PERMISSION_GRANTED
4454            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4455                != PackageManager.PERMISSION_GRANTED) {
4456            throw new SecurityException(message + " requires "
4457                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4458                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4459        }
4460    }
4461
4462    @Override
4463    public boolean shouldShowRequestPermissionRationale(String permissionName,
4464            String packageName, int userId) {
4465        if (UserHandle.getCallingUserId() != userId) {
4466            mContext.enforceCallingPermission(
4467                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4468                    "canShowRequestPermissionRationale for user " + userId);
4469        }
4470
4471        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4472        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4473            return false;
4474        }
4475
4476        if (checkPermission(permissionName, packageName, userId)
4477                == PackageManager.PERMISSION_GRANTED) {
4478            return false;
4479        }
4480
4481        final int flags;
4482
4483        final long identity = Binder.clearCallingIdentity();
4484        try {
4485            flags = getPermissionFlags(permissionName,
4486                    packageName, userId);
4487        } finally {
4488            Binder.restoreCallingIdentity(identity);
4489        }
4490
4491        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4492                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4493                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4494
4495        if ((flags & fixedFlags) != 0) {
4496            return false;
4497        }
4498
4499        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4500    }
4501
4502    @Override
4503    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4504        mContext.enforceCallingOrSelfPermission(
4505                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4506                "addOnPermissionsChangeListener");
4507
4508        synchronized (mPackages) {
4509            mOnPermissionChangeListeners.addListenerLocked(listener);
4510        }
4511    }
4512
4513    @Override
4514    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4515        synchronized (mPackages) {
4516            mOnPermissionChangeListeners.removeListenerLocked(listener);
4517        }
4518    }
4519
4520    @Override
4521    public boolean isProtectedBroadcast(String actionName) {
4522        synchronized (mPackages) {
4523            if (mProtectedBroadcasts.contains(actionName)) {
4524                return true;
4525            } else if (actionName != null) {
4526                // TODO: remove these terrible hacks
4527                if (actionName.startsWith("android.net.netmon.lingerExpired")
4528                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4529                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4530                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4531                    return true;
4532                }
4533            }
4534        }
4535        return false;
4536    }
4537
4538    @Override
4539    public int checkSignatures(String pkg1, String pkg2) {
4540        synchronized (mPackages) {
4541            final PackageParser.Package p1 = mPackages.get(pkg1);
4542            final PackageParser.Package p2 = mPackages.get(pkg2);
4543            if (p1 == null || p1.mExtras == null
4544                    || p2 == null || p2.mExtras == null) {
4545                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4546            }
4547            return compareSignatures(p1.mSignatures, p2.mSignatures);
4548        }
4549    }
4550
4551    @Override
4552    public int checkUidSignatures(int uid1, int uid2) {
4553        // Map to base uids.
4554        uid1 = UserHandle.getAppId(uid1);
4555        uid2 = UserHandle.getAppId(uid2);
4556        // reader
4557        synchronized (mPackages) {
4558            Signature[] s1;
4559            Signature[] s2;
4560            Object obj = mSettings.getUserIdLPr(uid1);
4561            if (obj != null) {
4562                if (obj instanceof SharedUserSetting) {
4563                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4564                } else if (obj instanceof PackageSetting) {
4565                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4566                } else {
4567                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4568                }
4569            } else {
4570                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4571            }
4572            obj = mSettings.getUserIdLPr(uid2);
4573            if (obj != null) {
4574                if (obj instanceof SharedUserSetting) {
4575                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4576                } else if (obj instanceof PackageSetting) {
4577                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4578                } else {
4579                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4580                }
4581            } else {
4582                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4583            }
4584            return compareSignatures(s1, s2);
4585        }
4586    }
4587
4588    /**
4589     * This method should typically only be used when granting or revoking
4590     * permissions, since the app may immediately restart after this call.
4591     * <p>
4592     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
4593     * guard your work against the app being relaunched.
4594     */
4595    private void killUid(int appId, int userId, String reason) {
4596        final long identity = Binder.clearCallingIdentity();
4597        try {
4598            IActivityManager am = ActivityManagerNative.getDefault();
4599            if (am != null) {
4600                try {
4601                    am.killUid(appId, userId, reason);
4602                } catch (RemoteException e) {
4603                    /* ignore - same process */
4604                }
4605            }
4606        } finally {
4607            Binder.restoreCallingIdentity(identity);
4608        }
4609    }
4610
4611    /**
4612     * Compares two sets of signatures. Returns:
4613     * <br />
4614     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4615     * <br />
4616     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4617     * <br />
4618     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4619     * <br />
4620     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4621     * <br />
4622     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4623     */
4624    static int compareSignatures(Signature[] s1, Signature[] s2) {
4625        if (s1 == null) {
4626            return s2 == null
4627                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4628                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4629        }
4630
4631        if (s2 == null) {
4632            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4633        }
4634
4635        if (s1.length != s2.length) {
4636            return PackageManager.SIGNATURE_NO_MATCH;
4637        }
4638
4639        // Since both signature sets are of size 1, we can compare without HashSets.
4640        if (s1.length == 1) {
4641            return s1[0].equals(s2[0]) ?
4642                    PackageManager.SIGNATURE_MATCH :
4643                    PackageManager.SIGNATURE_NO_MATCH;
4644        }
4645
4646        ArraySet<Signature> set1 = new ArraySet<Signature>();
4647        for (Signature sig : s1) {
4648            set1.add(sig);
4649        }
4650        ArraySet<Signature> set2 = new ArraySet<Signature>();
4651        for (Signature sig : s2) {
4652            set2.add(sig);
4653        }
4654        // Make sure s2 contains all signatures in s1.
4655        if (set1.equals(set2)) {
4656            return PackageManager.SIGNATURE_MATCH;
4657        }
4658        return PackageManager.SIGNATURE_NO_MATCH;
4659    }
4660
4661    /**
4662     * If the database version for this type of package (internal storage or
4663     * external storage) is less than the version where package signatures
4664     * were updated, return true.
4665     */
4666    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4667        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4668        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4669    }
4670
4671    /**
4672     * Used for backward compatibility to make sure any packages with
4673     * certificate chains get upgraded to the new style. {@code existingSigs}
4674     * will be in the old format (since they were stored on disk from before the
4675     * system upgrade) and {@code scannedSigs} will be in the newer format.
4676     */
4677    private int compareSignaturesCompat(PackageSignatures existingSigs,
4678            PackageParser.Package scannedPkg) {
4679        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4680            return PackageManager.SIGNATURE_NO_MATCH;
4681        }
4682
4683        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4684        for (Signature sig : existingSigs.mSignatures) {
4685            existingSet.add(sig);
4686        }
4687        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4688        for (Signature sig : scannedPkg.mSignatures) {
4689            try {
4690                Signature[] chainSignatures = sig.getChainSignatures();
4691                for (Signature chainSig : chainSignatures) {
4692                    scannedCompatSet.add(chainSig);
4693                }
4694            } catch (CertificateEncodingException e) {
4695                scannedCompatSet.add(sig);
4696            }
4697        }
4698        /*
4699         * Make sure the expanded scanned set contains all signatures in the
4700         * existing one.
4701         */
4702        if (scannedCompatSet.equals(existingSet)) {
4703            // Migrate the old signatures to the new scheme.
4704            existingSigs.assignSignatures(scannedPkg.mSignatures);
4705            // The new KeySets will be re-added later in the scanning process.
4706            synchronized (mPackages) {
4707                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4708            }
4709            return PackageManager.SIGNATURE_MATCH;
4710        }
4711        return PackageManager.SIGNATURE_NO_MATCH;
4712    }
4713
4714    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4715        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4716        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4717    }
4718
4719    private int compareSignaturesRecover(PackageSignatures existingSigs,
4720            PackageParser.Package scannedPkg) {
4721        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4722            return PackageManager.SIGNATURE_NO_MATCH;
4723        }
4724
4725        String msg = null;
4726        try {
4727            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4728                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4729                        + scannedPkg.packageName);
4730                return PackageManager.SIGNATURE_MATCH;
4731            }
4732        } catch (CertificateException e) {
4733            msg = e.getMessage();
4734        }
4735
4736        logCriticalInfo(Log.INFO,
4737                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4738        return PackageManager.SIGNATURE_NO_MATCH;
4739    }
4740
4741    @Override
4742    public List<String> getAllPackages() {
4743        synchronized (mPackages) {
4744            return new ArrayList<String>(mPackages.keySet());
4745        }
4746    }
4747
4748    @Override
4749    public String[] getPackagesForUid(int uid) {
4750        uid = UserHandle.getAppId(uid);
4751        // reader
4752        synchronized (mPackages) {
4753            Object obj = mSettings.getUserIdLPr(uid);
4754            if (obj instanceof SharedUserSetting) {
4755                final SharedUserSetting sus = (SharedUserSetting) obj;
4756                final int N = sus.packages.size();
4757                final String[] res = new String[N];
4758                final Iterator<PackageSetting> it = sus.packages.iterator();
4759                int i = 0;
4760                while (it.hasNext()) {
4761                    res[i++] = it.next().name;
4762                }
4763                return res;
4764            } else if (obj instanceof PackageSetting) {
4765                final PackageSetting ps = (PackageSetting) obj;
4766                return new String[] { ps.name };
4767            }
4768        }
4769        return null;
4770    }
4771
4772    @Override
4773    public String getNameForUid(int uid) {
4774        // reader
4775        synchronized (mPackages) {
4776            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4777            if (obj instanceof SharedUserSetting) {
4778                final SharedUserSetting sus = (SharedUserSetting) obj;
4779                return sus.name + ":" + sus.userId;
4780            } else if (obj instanceof PackageSetting) {
4781                final PackageSetting ps = (PackageSetting) obj;
4782                return ps.name;
4783            }
4784        }
4785        return null;
4786    }
4787
4788    @Override
4789    public int getUidForSharedUser(String sharedUserName) {
4790        if(sharedUserName == null) {
4791            return -1;
4792        }
4793        // reader
4794        synchronized (mPackages) {
4795            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4796            if (suid == null) {
4797                return -1;
4798            }
4799            return suid.userId;
4800        }
4801    }
4802
4803    @Override
4804    public int getFlagsForUid(int uid) {
4805        synchronized (mPackages) {
4806            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4807            if (obj instanceof SharedUserSetting) {
4808                final SharedUserSetting sus = (SharedUserSetting) obj;
4809                return sus.pkgFlags;
4810            } else if (obj instanceof PackageSetting) {
4811                final PackageSetting ps = (PackageSetting) obj;
4812                return ps.pkgFlags;
4813            }
4814        }
4815        return 0;
4816    }
4817
4818    @Override
4819    public int getPrivateFlagsForUid(int uid) {
4820        synchronized (mPackages) {
4821            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4822            if (obj instanceof SharedUserSetting) {
4823                final SharedUserSetting sus = (SharedUserSetting) obj;
4824                return sus.pkgPrivateFlags;
4825            } else if (obj instanceof PackageSetting) {
4826                final PackageSetting ps = (PackageSetting) obj;
4827                return ps.pkgPrivateFlags;
4828            }
4829        }
4830        return 0;
4831    }
4832
4833    @Override
4834    public boolean isUidPrivileged(int uid) {
4835        uid = UserHandle.getAppId(uid);
4836        // reader
4837        synchronized (mPackages) {
4838            Object obj = mSettings.getUserIdLPr(uid);
4839            if (obj instanceof SharedUserSetting) {
4840                final SharedUserSetting sus = (SharedUserSetting) obj;
4841                final Iterator<PackageSetting> it = sus.packages.iterator();
4842                while (it.hasNext()) {
4843                    if (it.next().isPrivileged()) {
4844                        return true;
4845                    }
4846                }
4847            } else if (obj instanceof PackageSetting) {
4848                final PackageSetting ps = (PackageSetting) obj;
4849                return ps.isPrivileged();
4850            }
4851        }
4852        return false;
4853    }
4854
4855    @Override
4856    public String[] getAppOpPermissionPackages(String permissionName) {
4857        synchronized (mPackages) {
4858            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4859            if (pkgs == null) {
4860                return null;
4861            }
4862            return pkgs.toArray(new String[pkgs.size()]);
4863        }
4864    }
4865
4866    @Override
4867    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4868            int flags, int userId) {
4869        try {
4870            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
4871
4872            if (!sUserManager.exists(userId)) return null;
4873            flags = updateFlagsForResolve(flags, userId, intent);
4874            enforceCrossUserPermission(Binder.getCallingUid(), userId,
4875                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
4876
4877            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
4878            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
4879                    flags, userId);
4880            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4881
4882            final ResolveInfo bestChoice =
4883                    chooseBestActivity(intent, resolvedType, flags, query, userId);
4884
4885            if (isEphemeralAllowed(intent, query, userId)) {
4886                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
4887                final EphemeralResolveInfo ai =
4888                        getEphemeralResolveInfo(intent, resolvedType, userId);
4889                if (ai != null) {
4890                    if (DEBUG_EPHEMERAL) {
4891                        Slog.v(TAG, "Returning an EphemeralResolveInfo");
4892                    }
4893                    bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4894                    bestChoice.ephemeralResolveInfo = ai;
4895                }
4896                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4897            }
4898            return bestChoice;
4899        } finally {
4900            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4901        }
4902    }
4903
4904    @Override
4905    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4906            IntentFilter filter, int match, ComponentName activity) {
4907        final int userId = UserHandle.getCallingUserId();
4908        if (DEBUG_PREFERRED) {
4909            Log.v(TAG, "setLastChosenActivity intent=" + intent
4910                + " resolvedType=" + resolvedType
4911                + " flags=" + flags
4912                + " filter=" + filter
4913                + " match=" + match
4914                + " activity=" + activity);
4915            filter.dump(new PrintStreamPrinter(System.out), "    ");
4916        }
4917        intent.setComponent(null);
4918        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4919                userId);
4920        // Find any earlier preferred or last chosen entries and nuke them
4921        findPreferredActivity(intent, resolvedType,
4922                flags, query, 0, false, true, false, userId);
4923        // Add the new activity as the last chosen for this filter
4924        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4925                "Setting last chosen");
4926    }
4927
4928    @Override
4929    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4930        final int userId = UserHandle.getCallingUserId();
4931        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4932        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4933                userId);
4934        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4935                false, false, false, userId);
4936    }
4937
4938
4939    private boolean isEphemeralAllowed(
4940            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4941        // Short circuit and return early if possible.
4942        if (DISABLE_EPHEMERAL_APPS) {
4943            return false;
4944        }
4945        final int callingUser = UserHandle.getCallingUserId();
4946        if (callingUser != UserHandle.USER_SYSTEM) {
4947            return false;
4948        }
4949        if (mEphemeralResolverConnection == null) {
4950            return false;
4951        }
4952        if (intent.getComponent() != null) {
4953            return false;
4954        }
4955        if (intent.getPackage() != null) {
4956            return false;
4957        }
4958        final boolean isWebUri = hasWebURI(intent);
4959        if (!isWebUri) {
4960            return false;
4961        }
4962        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4963        synchronized (mPackages) {
4964            final int count = resolvedActivites.size();
4965            for (int n = 0; n < count; n++) {
4966                ResolveInfo info = resolvedActivites.get(n);
4967                String packageName = info.activityInfo.packageName;
4968                PackageSetting ps = mSettings.mPackages.get(packageName);
4969                if (ps != null) {
4970                    // Try to get the status from User settings first
4971                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4972                    int status = (int) (packedStatus >> 32);
4973                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4974                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4975                        if (DEBUG_EPHEMERAL) {
4976                            Slog.v(TAG, "DENY ephemeral apps;"
4977                                + " pkg: " + packageName + ", status: " + status);
4978                        }
4979                        return false;
4980                    }
4981                }
4982            }
4983        }
4984        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4985        return true;
4986    }
4987
4988    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4989            int userId) {
4990        MessageDigest digest = null;
4991        try {
4992            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4993        } catch (NoSuchAlgorithmException e) {
4994            // If we can't create a digest, ignore ephemeral apps.
4995            return null;
4996        }
4997
4998        final byte[] hostBytes = intent.getData().getHost().getBytes();
4999        final byte[] digestBytes = digest.digest(hostBytes);
5000        int shaPrefix =
5001                digestBytes[0] << 24
5002                | digestBytes[1] << 16
5003                | digestBytes[2] << 8
5004                | digestBytes[3] << 0;
5005        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
5006                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
5007        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
5008            // No hash prefix match; there are no ephemeral apps for this domain.
5009            return null;
5010        }
5011        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
5012            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
5013            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
5014                continue;
5015            }
5016            final List<IntentFilter> filters = ephemeralApplication.getFilters();
5017            // No filters; this should never happen.
5018            if (filters.isEmpty()) {
5019                continue;
5020            }
5021            // We have a domain match; resolve the filters to see if anything matches.
5022            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
5023            for (int j = filters.size() - 1; j >= 0; --j) {
5024                final EphemeralResolveIntentInfo intentInfo =
5025                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
5026                ephemeralResolver.addFilter(intentInfo);
5027            }
5028            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
5029                    intent, resolvedType, false /*defaultOnly*/, userId);
5030            if (!matchedResolveInfoList.isEmpty()) {
5031                return matchedResolveInfoList.get(0);
5032            }
5033        }
5034        // Hash or filter mis-match; no ephemeral apps for this domain.
5035        return null;
5036    }
5037
5038    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
5039            int flags, List<ResolveInfo> query, int userId) {
5040        if (query != null) {
5041            final int N = query.size();
5042            if (N == 1) {
5043                return query.get(0);
5044            } else if (N > 1) {
5045                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
5046                // If there is more than one activity with the same priority,
5047                // then let the user decide between them.
5048                ResolveInfo r0 = query.get(0);
5049                ResolveInfo r1 = query.get(1);
5050                if (DEBUG_INTENT_MATCHING || debug) {
5051                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
5052                            + r1.activityInfo.name + "=" + r1.priority);
5053                }
5054                // If the first activity has a higher priority, or a different
5055                // default, then it is always desirable to pick it.
5056                if (r0.priority != r1.priority
5057                        || r0.preferredOrder != r1.preferredOrder
5058                        || r0.isDefault != r1.isDefault) {
5059                    return query.get(0);
5060                }
5061                // If we have saved a preference for a preferred activity for
5062                // this Intent, use that.
5063                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
5064                        flags, query, r0.priority, true, false, debug, userId);
5065                if (ri != null) {
5066                    return ri;
5067                }
5068                ri = new ResolveInfo(mResolveInfo);
5069                ri.activityInfo = new ActivityInfo(ri.activityInfo);
5070                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
5071                // If all of the options come from the same package, show the application's
5072                // label and icon instead of the generic resolver's.
5073                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
5074                // and then throw away the ResolveInfo itself, meaning that the caller loses
5075                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
5076                // a fallback for this case; we only set the target package's resources on
5077                // the ResolveInfo, not the ActivityInfo.
5078                final String intentPackage = intent.getPackage();
5079                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
5080                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
5081                    ri.resolvePackageName = intentPackage;
5082                    if (userNeedsBadging(userId)) {
5083                        ri.noResourceId = true;
5084                    } else {
5085                        ri.icon = appi.icon;
5086                    }
5087                    ri.iconResourceId = appi.icon;
5088                    ri.labelRes = appi.labelRes;
5089                }
5090                ri.activityInfo.applicationInfo = new ApplicationInfo(
5091                        ri.activityInfo.applicationInfo);
5092                if (userId != 0) {
5093                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
5094                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
5095                }
5096                // Make sure that the resolver is displayable in car mode
5097                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
5098                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
5099                return ri;
5100            }
5101        }
5102        return null;
5103    }
5104
5105    /**
5106     * Return true if the given list is not empty and all of its contents have
5107     * an activityInfo with the given package name.
5108     */
5109    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
5110        if (ArrayUtils.isEmpty(list)) {
5111            return false;
5112        }
5113        for (int i = 0, N = list.size(); i < N; i++) {
5114            final ResolveInfo ri = list.get(i);
5115            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
5116            if (ai == null || !packageName.equals(ai.packageName)) {
5117                return false;
5118            }
5119        }
5120        return true;
5121    }
5122
5123    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
5124            int flags, List<ResolveInfo> query, boolean debug, int userId) {
5125        final int N = query.size();
5126        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
5127                .get(userId);
5128        // Get the list of persistent preferred activities that handle the intent
5129        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
5130        List<PersistentPreferredActivity> pprefs = ppir != null
5131                ? ppir.queryIntent(intent, resolvedType,
5132                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5133                : null;
5134        if (pprefs != null && pprefs.size() > 0) {
5135            final int M = pprefs.size();
5136            for (int i=0; i<M; i++) {
5137                final PersistentPreferredActivity ppa = pprefs.get(i);
5138                if (DEBUG_PREFERRED || debug) {
5139                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
5140                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
5141                            + "\n  component=" + ppa.mComponent);
5142                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5143                }
5144                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
5145                        flags | MATCH_DISABLED_COMPONENTS, userId);
5146                if (DEBUG_PREFERRED || debug) {
5147                    Slog.v(TAG, "Found persistent preferred activity:");
5148                    if (ai != null) {
5149                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5150                    } else {
5151                        Slog.v(TAG, "  null");
5152                    }
5153                }
5154                if (ai == null) {
5155                    // This previously registered persistent preferred activity
5156                    // component is no longer known. Ignore it and do NOT remove it.
5157                    continue;
5158                }
5159                for (int j=0; j<N; j++) {
5160                    final ResolveInfo ri = query.get(j);
5161                    if (!ri.activityInfo.applicationInfo.packageName
5162                            .equals(ai.applicationInfo.packageName)) {
5163                        continue;
5164                    }
5165                    if (!ri.activityInfo.name.equals(ai.name)) {
5166                        continue;
5167                    }
5168                    //  Found a persistent preference that can handle the intent.
5169                    if (DEBUG_PREFERRED || debug) {
5170                        Slog.v(TAG, "Returning persistent preferred activity: " +
5171                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5172                    }
5173                    return ri;
5174                }
5175            }
5176        }
5177        return null;
5178    }
5179
5180    // TODO: handle preferred activities missing while user has amnesia
5181    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
5182            List<ResolveInfo> query, int priority, boolean always,
5183            boolean removeMatches, boolean debug, int userId) {
5184        if (!sUserManager.exists(userId)) return null;
5185        flags = updateFlagsForResolve(flags, userId, intent);
5186        // writer
5187        synchronized (mPackages) {
5188            if (intent.getSelector() != null) {
5189                intent = intent.getSelector();
5190            }
5191            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5192
5193            // Try to find a matching persistent preferred activity.
5194            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
5195                    debug, userId);
5196
5197            // If a persistent preferred activity matched, use it.
5198            if (pri != null) {
5199                return pri;
5200            }
5201
5202            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
5203            // Get the list of preferred activities that handle the intent
5204            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
5205            List<PreferredActivity> prefs = pir != null
5206                    ? pir.queryIntent(intent, resolvedType,
5207                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
5208                    : null;
5209            if (prefs != null && prefs.size() > 0) {
5210                boolean changed = false;
5211                try {
5212                    // First figure out how good the original match set is.
5213                    // We will only allow preferred activities that came
5214                    // from the same match quality.
5215                    int match = 0;
5216
5217                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
5218
5219                    final int N = query.size();
5220                    for (int j=0; j<N; j++) {
5221                        final ResolveInfo ri = query.get(j);
5222                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
5223                                + ": 0x" + Integer.toHexString(match));
5224                        if (ri.match > match) {
5225                            match = ri.match;
5226                        }
5227                    }
5228
5229                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
5230                            + Integer.toHexString(match));
5231
5232                    match &= IntentFilter.MATCH_CATEGORY_MASK;
5233                    final int M = prefs.size();
5234                    for (int i=0; i<M; i++) {
5235                        final PreferredActivity pa = prefs.get(i);
5236                        if (DEBUG_PREFERRED || debug) {
5237                            Slog.v(TAG, "Checking PreferredActivity ds="
5238                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
5239                                    + "\n  component=" + pa.mPref.mComponent);
5240                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5241                        }
5242                        if (pa.mPref.mMatch != match) {
5243                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
5244                                    + Integer.toHexString(pa.mPref.mMatch));
5245                            continue;
5246                        }
5247                        // If it's not an "always" type preferred activity and that's what we're
5248                        // looking for, skip it.
5249                        if (always && !pa.mPref.mAlways) {
5250                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
5251                            continue;
5252                        }
5253                        final ActivityInfo ai = getActivityInfo(
5254                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5255                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5256                                userId);
5257                        if (DEBUG_PREFERRED || debug) {
5258                            Slog.v(TAG, "Found preferred activity:");
5259                            if (ai != null) {
5260                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5261                            } else {
5262                                Slog.v(TAG, "  null");
5263                            }
5264                        }
5265                        if (ai == null) {
5266                            // This previously registered preferred activity
5267                            // component is no longer known.  Most likely an update
5268                            // to the app was installed and in the new version this
5269                            // component no longer exists.  Clean it up by removing
5270                            // it from the preferred activities list, and skip it.
5271                            Slog.w(TAG, "Removing dangling preferred activity: "
5272                                    + pa.mPref.mComponent);
5273                            pir.removeFilter(pa);
5274                            changed = true;
5275                            continue;
5276                        }
5277                        for (int j=0; j<N; j++) {
5278                            final ResolveInfo ri = query.get(j);
5279                            if (!ri.activityInfo.applicationInfo.packageName
5280                                    .equals(ai.applicationInfo.packageName)) {
5281                                continue;
5282                            }
5283                            if (!ri.activityInfo.name.equals(ai.name)) {
5284                                continue;
5285                            }
5286
5287                            if (removeMatches) {
5288                                pir.removeFilter(pa);
5289                                changed = true;
5290                                if (DEBUG_PREFERRED) {
5291                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5292                                }
5293                                break;
5294                            }
5295
5296                            // Okay we found a previously set preferred or last chosen app.
5297                            // If the result set is different from when this
5298                            // was created, we need to clear it and re-ask the
5299                            // user their preference, if we're looking for an "always" type entry.
5300                            if (always && !pa.mPref.sameSet(query)) {
5301                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5302                                        + intent + " type " + resolvedType);
5303                                if (DEBUG_PREFERRED) {
5304                                    Slog.v(TAG, "Removing preferred activity since set changed "
5305                                            + pa.mPref.mComponent);
5306                                }
5307                                pir.removeFilter(pa);
5308                                // Re-add the filter as a "last chosen" entry (!always)
5309                                PreferredActivity lastChosen = new PreferredActivity(
5310                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5311                                pir.addFilter(lastChosen);
5312                                changed = true;
5313                                return null;
5314                            }
5315
5316                            // Yay! Either the set matched or we're looking for the last chosen
5317                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5318                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5319                            return ri;
5320                        }
5321                    }
5322                } finally {
5323                    if (changed) {
5324                        if (DEBUG_PREFERRED) {
5325                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5326                        }
5327                        scheduleWritePackageRestrictionsLocked(userId);
5328                    }
5329                }
5330            }
5331        }
5332        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5333        return null;
5334    }
5335
5336    /*
5337     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5338     */
5339    @Override
5340    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5341            int targetUserId) {
5342        mContext.enforceCallingOrSelfPermission(
5343                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5344        List<CrossProfileIntentFilter> matches =
5345                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5346        if (matches != null) {
5347            int size = matches.size();
5348            for (int i = 0; i < size; i++) {
5349                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5350            }
5351        }
5352        if (hasWebURI(intent)) {
5353            // cross-profile app linking works only towards the parent.
5354            final UserInfo parent = getProfileParent(sourceUserId);
5355            synchronized(mPackages) {
5356                int flags = updateFlagsForResolve(0, parent.id, intent);
5357                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5358                        intent, resolvedType, flags, sourceUserId, parent.id);
5359                return xpDomainInfo != null;
5360            }
5361        }
5362        return false;
5363    }
5364
5365    private UserInfo getProfileParent(int userId) {
5366        final long identity = Binder.clearCallingIdentity();
5367        try {
5368            return sUserManager.getProfileParent(userId);
5369        } finally {
5370            Binder.restoreCallingIdentity(identity);
5371        }
5372    }
5373
5374    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5375            String resolvedType, int userId) {
5376        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5377        if (resolver != null) {
5378            return resolver.queryIntent(intent, resolvedType, false, userId);
5379        }
5380        return null;
5381    }
5382
5383    @Override
5384    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5385            String resolvedType, int flags, int userId) {
5386        try {
5387            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5388
5389            return new ParceledListSlice<>(
5390                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5391        } finally {
5392            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5393        }
5394    }
5395
5396    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5397            String resolvedType, int flags, int userId) {
5398        if (!sUserManager.exists(userId)) return Collections.emptyList();
5399        flags = updateFlagsForResolve(flags, userId, intent);
5400        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5401                false /* requireFullPermission */, false /* checkShell */,
5402                "query intent activities");
5403        ComponentName comp = intent.getComponent();
5404        if (comp == null) {
5405            if (intent.getSelector() != null) {
5406                intent = intent.getSelector();
5407                comp = intent.getComponent();
5408            }
5409        }
5410
5411        if (comp != null) {
5412            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5413            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5414            if (ai != null) {
5415                final ResolveInfo ri = new ResolveInfo();
5416                ri.activityInfo = ai;
5417                list.add(ri);
5418            }
5419            return list;
5420        }
5421
5422        // reader
5423        synchronized (mPackages) {
5424            final String pkgName = intent.getPackage();
5425            if (pkgName == null) {
5426                List<CrossProfileIntentFilter> matchingFilters =
5427                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5428                // Check for results that need to skip the current profile.
5429                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5430                        resolvedType, flags, userId);
5431                if (xpResolveInfo != null) {
5432                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5433                    result.add(xpResolveInfo);
5434                    return filterIfNotSystemUser(result, userId);
5435                }
5436
5437                // Check for results in the current profile.
5438                List<ResolveInfo> result = mActivities.queryIntent(
5439                        intent, resolvedType, flags, userId);
5440                result = filterIfNotSystemUser(result, userId);
5441
5442                // Check for cross profile results.
5443                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5444                xpResolveInfo = queryCrossProfileIntents(
5445                        matchingFilters, intent, resolvedType, flags, userId,
5446                        hasNonNegativePriorityResult);
5447                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5448                    boolean isVisibleToUser = filterIfNotSystemUser(
5449                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5450                    if (isVisibleToUser) {
5451                        result.add(xpResolveInfo);
5452                        Collections.sort(result, mResolvePrioritySorter);
5453                    }
5454                }
5455                if (hasWebURI(intent)) {
5456                    CrossProfileDomainInfo xpDomainInfo = null;
5457                    final UserInfo parent = getProfileParent(userId);
5458                    if (parent != null) {
5459                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5460                                flags, userId, parent.id);
5461                    }
5462                    if (xpDomainInfo != null) {
5463                        if (xpResolveInfo != null) {
5464                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5465                            // in the result.
5466                            result.remove(xpResolveInfo);
5467                        }
5468                        if (result.size() == 0) {
5469                            result.add(xpDomainInfo.resolveInfo);
5470                            return result;
5471                        }
5472                    } else if (result.size() <= 1) {
5473                        return result;
5474                    }
5475                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5476                            xpDomainInfo, userId);
5477                    Collections.sort(result, mResolvePrioritySorter);
5478                }
5479                return result;
5480            }
5481            final PackageParser.Package pkg = mPackages.get(pkgName);
5482            if (pkg != null) {
5483                return filterIfNotSystemUser(
5484                        mActivities.queryIntentForPackage(
5485                                intent, resolvedType, flags, pkg.activities, userId),
5486                        userId);
5487            }
5488            return new ArrayList<ResolveInfo>();
5489        }
5490    }
5491
5492    private static class CrossProfileDomainInfo {
5493        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5494        ResolveInfo resolveInfo;
5495        /* Best domain verification status of the activities found in the other profile */
5496        int bestDomainVerificationStatus;
5497    }
5498
5499    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5500            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5501        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5502                sourceUserId)) {
5503            return null;
5504        }
5505        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5506                resolvedType, flags, parentUserId);
5507
5508        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5509            return null;
5510        }
5511        CrossProfileDomainInfo result = null;
5512        int size = resultTargetUser.size();
5513        for (int i = 0; i < size; i++) {
5514            ResolveInfo riTargetUser = resultTargetUser.get(i);
5515            // Intent filter verification is only for filters that specify a host. So don't return
5516            // those that handle all web uris.
5517            if (riTargetUser.handleAllWebDataURI) {
5518                continue;
5519            }
5520            String packageName = riTargetUser.activityInfo.packageName;
5521            PackageSetting ps = mSettings.mPackages.get(packageName);
5522            if (ps == null) {
5523                continue;
5524            }
5525            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5526            int status = (int)(verificationState >> 32);
5527            if (result == null) {
5528                result = new CrossProfileDomainInfo();
5529                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5530                        sourceUserId, parentUserId);
5531                result.bestDomainVerificationStatus = status;
5532            } else {
5533                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5534                        result.bestDomainVerificationStatus);
5535            }
5536        }
5537        // Don't consider matches with status NEVER across profiles.
5538        if (result != null && result.bestDomainVerificationStatus
5539                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5540            return null;
5541        }
5542        return result;
5543    }
5544
5545    /**
5546     * Verification statuses are ordered from the worse to the best, except for
5547     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5548     */
5549    private int bestDomainVerificationStatus(int status1, int status2) {
5550        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5551            return status2;
5552        }
5553        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5554            return status1;
5555        }
5556        return (int) MathUtils.max(status1, status2);
5557    }
5558
5559    private boolean isUserEnabled(int userId) {
5560        long callingId = Binder.clearCallingIdentity();
5561        try {
5562            UserInfo userInfo = sUserManager.getUserInfo(userId);
5563            return userInfo != null && userInfo.isEnabled();
5564        } finally {
5565            Binder.restoreCallingIdentity(callingId);
5566        }
5567    }
5568
5569    /**
5570     * Filter out activities with systemUserOnly flag set, when current user is not System.
5571     *
5572     * @return filtered list
5573     */
5574    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5575        if (userId == UserHandle.USER_SYSTEM) {
5576            return resolveInfos;
5577        }
5578        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5579            ResolveInfo info = resolveInfos.get(i);
5580            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5581                resolveInfos.remove(i);
5582            }
5583        }
5584        return resolveInfos;
5585    }
5586
5587    /**
5588     * @param resolveInfos list of resolve infos in descending priority order
5589     * @return if the list contains a resolve info with non-negative priority
5590     */
5591    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5592        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5593    }
5594
5595    private static boolean hasWebURI(Intent intent) {
5596        if (intent.getData() == null) {
5597            return false;
5598        }
5599        final String scheme = intent.getScheme();
5600        if (TextUtils.isEmpty(scheme)) {
5601            return false;
5602        }
5603        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5604    }
5605
5606    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5607            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5608            int userId) {
5609        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5610
5611        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5612            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5613                    candidates.size());
5614        }
5615
5616        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5617        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5618        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5619        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5620        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5621        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5622
5623        synchronized (mPackages) {
5624            final int count = candidates.size();
5625            // First, try to use linked apps. Partition the candidates into four lists:
5626            // one for the final results, one for the "do not use ever", one for "undefined status"
5627            // and finally one for "browser app type".
5628            for (int n=0; n<count; n++) {
5629                ResolveInfo info = candidates.get(n);
5630                String packageName = info.activityInfo.packageName;
5631                PackageSetting ps = mSettings.mPackages.get(packageName);
5632                if (ps != null) {
5633                    // Add to the special match all list (Browser use case)
5634                    if (info.handleAllWebDataURI) {
5635                        matchAllList.add(info);
5636                        continue;
5637                    }
5638                    // Try to get the status from User settings first
5639                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5640                    int status = (int)(packedStatus >> 32);
5641                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5642                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5643                        if (DEBUG_DOMAIN_VERIFICATION) {
5644                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5645                                    + " : linkgen=" + linkGeneration);
5646                        }
5647                        // Use link-enabled generation as preferredOrder, i.e.
5648                        // prefer newly-enabled over earlier-enabled.
5649                        info.preferredOrder = linkGeneration;
5650                        alwaysList.add(info);
5651                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5652                        if (DEBUG_DOMAIN_VERIFICATION) {
5653                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5654                        }
5655                        neverList.add(info);
5656                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5657                        if (DEBUG_DOMAIN_VERIFICATION) {
5658                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5659                        }
5660                        alwaysAskList.add(info);
5661                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5662                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5663                        if (DEBUG_DOMAIN_VERIFICATION) {
5664                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5665                        }
5666                        undefinedList.add(info);
5667                    }
5668                }
5669            }
5670
5671            // We'll want to include browser possibilities in a few cases
5672            boolean includeBrowser = false;
5673
5674            // First try to add the "always" resolution(s) for the current user, if any
5675            if (alwaysList.size() > 0) {
5676                result.addAll(alwaysList);
5677            } else {
5678                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5679                result.addAll(undefinedList);
5680                // Maybe add one for the other profile.
5681                if (xpDomainInfo != null && (
5682                        xpDomainInfo.bestDomainVerificationStatus
5683                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5684                    result.add(xpDomainInfo.resolveInfo);
5685                }
5686                includeBrowser = true;
5687            }
5688
5689            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5690            // If there were 'always' entries their preferred order has been set, so we also
5691            // back that off to make the alternatives equivalent
5692            if (alwaysAskList.size() > 0) {
5693                for (ResolveInfo i : result) {
5694                    i.preferredOrder = 0;
5695                }
5696                result.addAll(alwaysAskList);
5697                includeBrowser = true;
5698            }
5699
5700            if (includeBrowser) {
5701                // Also add browsers (all of them or only the default one)
5702                if (DEBUG_DOMAIN_VERIFICATION) {
5703                    Slog.v(TAG, "   ...including browsers in candidate set");
5704                }
5705                if ((matchFlags & MATCH_ALL) != 0) {
5706                    result.addAll(matchAllList);
5707                } else {
5708                    // Browser/generic handling case.  If there's a default browser, go straight
5709                    // to that (but only if there is no other higher-priority match).
5710                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5711                    int maxMatchPrio = 0;
5712                    ResolveInfo defaultBrowserMatch = null;
5713                    final int numCandidates = matchAllList.size();
5714                    for (int n = 0; n < numCandidates; n++) {
5715                        ResolveInfo info = matchAllList.get(n);
5716                        // track the highest overall match priority...
5717                        if (info.priority > maxMatchPrio) {
5718                            maxMatchPrio = info.priority;
5719                        }
5720                        // ...and the highest-priority default browser match
5721                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5722                            if (defaultBrowserMatch == null
5723                                    || (defaultBrowserMatch.priority < info.priority)) {
5724                                if (debug) {
5725                                    Slog.v(TAG, "Considering default browser match " + info);
5726                                }
5727                                defaultBrowserMatch = info;
5728                            }
5729                        }
5730                    }
5731                    if (defaultBrowserMatch != null
5732                            && defaultBrowserMatch.priority >= maxMatchPrio
5733                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5734                    {
5735                        if (debug) {
5736                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5737                        }
5738                        result.add(defaultBrowserMatch);
5739                    } else {
5740                        result.addAll(matchAllList);
5741                    }
5742                }
5743
5744                // If there is nothing selected, add all candidates and remove the ones that the user
5745                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5746                if (result.size() == 0) {
5747                    result.addAll(candidates);
5748                    result.removeAll(neverList);
5749                }
5750            }
5751        }
5752        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5753            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5754                    result.size());
5755            for (ResolveInfo info : result) {
5756                Slog.v(TAG, "  + " + info.activityInfo);
5757            }
5758        }
5759        return result;
5760    }
5761
5762    // Returns a packed value as a long:
5763    //
5764    // high 'int'-sized word: link status: undefined/ask/never/always.
5765    // low 'int'-sized word: relative priority among 'always' results.
5766    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5767        long result = ps.getDomainVerificationStatusForUser(userId);
5768        // if none available, get the master status
5769        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5770            if (ps.getIntentFilterVerificationInfo() != null) {
5771                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5772            }
5773        }
5774        return result;
5775    }
5776
5777    private ResolveInfo querySkipCurrentProfileIntents(
5778            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5779            int flags, int sourceUserId) {
5780        if (matchingFilters != null) {
5781            int size = matchingFilters.size();
5782            for (int i = 0; i < size; i ++) {
5783                CrossProfileIntentFilter filter = matchingFilters.get(i);
5784                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5785                    // Checking if there are activities in the target user that can handle the
5786                    // intent.
5787                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5788                            resolvedType, flags, sourceUserId);
5789                    if (resolveInfo != null) {
5790                        return resolveInfo;
5791                    }
5792                }
5793            }
5794        }
5795        return null;
5796    }
5797
5798    // Return matching ResolveInfo in target user if any.
5799    private ResolveInfo queryCrossProfileIntents(
5800            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5801            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5802        if (matchingFilters != null) {
5803            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5804            // match the same intent. For performance reasons, it is better not to
5805            // run queryIntent twice for the same userId
5806            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5807            int size = matchingFilters.size();
5808            for (int i = 0; i < size; i++) {
5809                CrossProfileIntentFilter filter = matchingFilters.get(i);
5810                int targetUserId = filter.getTargetUserId();
5811                boolean skipCurrentProfile =
5812                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5813                boolean skipCurrentProfileIfNoMatchFound =
5814                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5815                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5816                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5817                    // Checking if there are activities in the target user that can handle the
5818                    // intent.
5819                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5820                            resolvedType, flags, sourceUserId);
5821                    if (resolveInfo != null) return resolveInfo;
5822                    alreadyTriedUserIds.put(targetUserId, true);
5823                }
5824            }
5825        }
5826        return null;
5827    }
5828
5829    /**
5830     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5831     * will forward the intent to the filter's target user.
5832     * Otherwise, returns null.
5833     */
5834    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5835            String resolvedType, int flags, int sourceUserId) {
5836        int targetUserId = filter.getTargetUserId();
5837        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5838                resolvedType, flags, targetUserId);
5839        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5840            // If all the matches in the target profile are suspended, return null.
5841            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5842                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5843                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5844                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5845                            targetUserId);
5846                }
5847            }
5848        }
5849        return null;
5850    }
5851
5852    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5853            int sourceUserId, int targetUserId) {
5854        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5855        long ident = Binder.clearCallingIdentity();
5856        boolean targetIsProfile;
5857        try {
5858            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5859        } finally {
5860            Binder.restoreCallingIdentity(ident);
5861        }
5862        String className;
5863        if (targetIsProfile) {
5864            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5865        } else {
5866            className = FORWARD_INTENT_TO_PARENT;
5867        }
5868        ComponentName forwardingActivityComponentName = new ComponentName(
5869                mAndroidApplication.packageName, className);
5870        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5871                sourceUserId);
5872        if (!targetIsProfile) {
5873            forwardingActivityInfo.showUserIcon = targetUserId;
5874            forwardingResolveInfo.noResourceId = true;
5875        }
5876        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5877        forwardingResolveInfo.priority = 0;
5878        forwardingResolveInfo.preferredOrder = 0;
5879        forwardingResolveInfo.match = 0;
5880        forwardingResolveInfo.isDefault = true;
5881        forwardingResolveInfo.filter = filter;
5882        forwardingResolveInfo.targetUserId = targetUserId;
5883        return forwardingResolveInfo;
5884    }
5885
5886    @Override
5887    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5888            Intent[] specifics, String[] specificTypes, Intent intent,
5889            String resolvedType, int flags, int userId) {
5890        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5891                specificTypes, intent, resolvedType, flags, userId));
5892    }
5893
5894    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5895            Intent[] specifics, String[] specificTypes, Intent intent,
5896            String resolvedType, int flags, int userId) {
5897        if (!sUserManager.exists(userId)) return Collections.emptyList();
5898        flags = updateFlagsForResolve(flags, userId, intent);
5899        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5900                false /* requireFullPermission */, false /* checkShell */,
5901                "query intent activity options");
5902        final String resultsAction = intent.getAction();
5903
5904        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5905                | PackageManager.GET_RESOLVED_FILTER, userId);
5906
5907        if (DEBUG_INTENT_MATCHING) {
5908            Log.v(TAG, "Query " + intent + ": " + results);
5909        }
5910
5911        int specificsPos = 0;
5912        int N;
5913
5914        // todo: note that the algorithm used here is O(N^2).  This
5915        // isn't a problem in our current environment, but if we start running
5916        // into situations where we have more than 5 or 10 matches then this
5917        // should probably be changed to something smarter...
5918
5919        // First we go through and resolve each of the specific items
5920        // that were supplied, taking care of removing any corresponding
5921        // duplicate items in the generic resolve list.
5922        if (specifics != null) {
5923            for (int i=0; i<specifics.length; i++) {
5924                final Intent sintent = specifics[i];
5925                if (sintent == null) {
5926                    continue;
5927                }
5928
5929                if (DEBUG_INTENT_MATCHING) {
5930                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5931                }
5932
5933                String action = sintent.getAction();
5934                if (resultsAction != null && resultsAction.equals(action)) {
5935                    // If this action was explicitly requested, then don't
5936                    // remove things that have it.
5937                    action = null;
5938                }
5939
5940                ResolveInfo ri = null;
5941                ActivityInfo ai = null;
5942
5943                ComponentName comp = sintent.getComponent();
5944                if (comp == null) {
5945                    ri = resolveIntent(
5946                        sintent,
5947                        specificTypes != null ? specificTypes[i] : null,
5948                            flags, userId);
5949                    if (ri == null) {
5950                        continue;
5951                    }
5952                    if (ri == mResolveInfo) {
5953                        // ACK!  Must do something better with this.
5954                    }
5955                    ai = ri.activityInfo;
5956                    comp = new ComponentName(ai.applicationInfo.packageName,
5957                            ai.name);
5958                } else {
5959                    ai = getActivityInfo(comp, flags, userId);
5960                    if (ai == null) {
5961                        continue;
5962                    }
5963                }
5964
5965                // Look for any generic query activities that are duplicates
5966                // of this specific one, and remove them from the results.
5967                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5968                N = results.size();
5969                int j;
5970                for (j=specificsPos; j<N; j++) {
5971                    ResolveInfo sri = results.get(j);
5972                    if ((sri.activityInfo.name.equals(comp.getClassName())
5973                            && sri.activityInfo.applicationInfo.packageName.equals(
5974                                    comp.getPackageName()))
5975                        || (action != null && sri.filter.matchAction(action))) {
5976                        results.remove(j);
5977                        if (DEBUG_INTENT_MATCHING) Log.v(
5978                            TAG, "Removing duplicate item from " + j
5979                            + " due to specific " + specificsPos);
5980                        if (ri == null) {
5981                            ri = sri;
5982                        }
5983                        j--;
5984                        N--;
5985                    }
5986                }
5987
5988                // Add this specific item to its proper place.
5989                if (ri == null) {
5990                    ri = new ResolveInfo();
5991                    ri.activityInfo = ai;
5992                }
5993                results.add(specificsPos, ri);
5994                ri.specificIndex = i;
5995                specificsPos++;
5996            }
5997        }
5998
5999        // Now we go through the remaining generic results and remove any
6000        // duplicate actions that are found here.
6001        N = results.size();
6002        for (int i=specificsPos; i<N-1; i++) {
6003            final ResolveInfo rii = results.get(i);
6004            if (rii.filter == null) {
6005                continue;
6006            }
6007
6008            // Iterate over all of the actions of this result's intent
6009            // filter...  typically this should be just one.
6010            final Iterator<String> it = rii.filter.actionsIterator();
6011            if (it == null) {
6012                continue;
6013            }
6014            while (it.hasNext()) {
6015                final String action = it.next();
6016                if (resultsAction != null && resultsAction.equals(action)) {
6017                    // If this action was explicitly requested, then don't
6018                    // remove things that have it.
6019                    continue;
6020                }
6021                for (int j=i+1; j<N; j++) {
6022                    final ResolveInfo rij = results.get(j);
6023                    if (rij.filter != null && rij.filter.hasAction(action)) {
6024                        results.remove(j);
6025                        if (DEBUG_INTENT_MATCHING) Log.v(
6026                            TAG, "Removing duplicate item from " + j
6027                            + " due to action " + action + " at " + i);
6028                        j--;
6029                        N--;
6030                    }
6031                }
6032            }
6033
6034            // If the caller didn't request filter information, drop it now
6035            // so we don't have to marshall/unmarshall it.
6036            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6037                rii.filter = null;
6038            }
6039        }
6040
6041        // Filter out the caller activity if so requested.
6042        if (caller != null) {
6043            N = results.size();
6044            for (int i=0; i<N; i++) {
6045                ActivityInfo ainfo = results.get(i).activityInfo;
6046                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
6047                        && caller.getClassName().equals(ainfo.name)) {
6048                    results.remove(i);
6049                    break;
6050                }
6051            }
6052        }
6053
6054        // If the caller didn't request filter information,
6055        // drop them now so we don't have to
6056        // marshall/unmarshall it.
6057        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
6058            N = results.size();
6059            for (int i=0; i<N; i++) {
6060                results.get(i).filter = null;
6061            }
6062        }
6063
6064        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
6065        return results;
6066    }
6067
6068    @Override
6069    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
6070            String resolvedType, int flags, int userId) {
6071        return new ParceledListSlice<>(
6072                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
6073    }
6074
6075    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
6076            String resolvedType, int flags, int userId) {
6077        if (!sUserManager.exists(userId)) return Collections.emptyList();
6078        flags = updateFlagsForResolve(flags, userId, intent);
6079        ComponentName comp = intent.getComponent();
6080        if (comp == null) {
6081            if (intent.getSelector() != null) {
6082                intent = intent.getSelector();
6083                comp = intent.getComponent();
6084            }
6085        }
6086        if (comp != null) {
6087            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6088            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
6089            if (ai != null) {
6090                ResolveInfo ri = new ResolveInfo();
6091                ri.activityInfo = ai;
6092                list.add(ri);
6093            }
6094            return list;
6095        }
6096
6097        // reader
6098        synchronized (mPackages) {
6099            String pkgName = intent.getPackage();
6100            if (pkgName == null) {
6101                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
6102            }
6103            final PackageParser.Package pkg = mPackages.get(pkgName);
6104            if (pkg != null) {
6105                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
6106                        userId);
6107            }
6108            return Collections.emptyList();
6109        }
6110    }
6111
6112    @Override
6113    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
6114        if (!sUserManager.exists(userId)) return null;
6115        flags = updateFlagsForResolve(flags, userId, intent);
6116        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
6117        if (query != null) {
6118            if (query.size() >= 1) {
6119                // If there is more than one service with the same priority,
6120                // just arbitrarily pick the first one.
6121                return query.get(0);
6122            }
6123        }
6124        return null;
6125    }
6126
6127    @Override
6128    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
6129            String resolvedType, int flags, int userId) {
6130        return new ParceledListSlice<>(
6131                queryIntentServicesInternal(intent, resolvedType, flags, userId));
6132    }
6133
6134    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
6135            String resolvedType, int flags, int userId) {
6136        if (!sUserManager.exists(userId)) return Collections.emptyList();
6137        flags = updateFlagsForResolve(flags, userId, intent);
6138        ComponentName comp = intent.getComponent();
6139        if (comp == null) {
6140            if (intent.getSelector() != null) {
6141                intent = intent.getSelector();
6142                comp = intent.getComponent();
6143            }
6144        }
6145        if (comp != null) {
6146            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6147            final ServiceInfo si = getServiceInfo(comp, flags, userId);
6148            if (si != null) {
6149                final ResolveInfo ri = new ResolveInfo();
6150                ri.serviceInfo = si;
6151                list.add(ri);
6152            }
6153            return list;
6154        }
6155
6156        // reader
6157        synchronized (mPackages) {
6158            String pkgName = intent.getPackage();
6159            if (pkgName == null) {
6160                return mServices.queryIntent(intent, resolvedType, flags, userId);
6161            }
6162            final PackageParser.Package pkg = mPackages.get(pkgName);
6163            if (pkg != null) {
6164                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
6165                        userId);
6166            }
6167            return Collections.emptyList();
6168        }
6169    }
6170
6171    @Override
6172    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
6173            String resolvedType, int flags, int userId) {
6174        return new ParceledListSlice<>(
6175                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
6176    }
6177
6178    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
6179            Intent intent, String resolvedType, int flags, int userId) {
6180        if (!sUserManager.exists(userId)) return Collections.emptyList();
6181        flags = updateFlagsForResolve(flags, userId, intent);
6182        ComponentName comp = intent.getComponent();
6183        if (comp == null) {
6184            if (intent.getSelector() != null) {
6185                intent = intent.getSelector();
6186                comp = intent.getComponent();
6187            }
6188        }
6189        if (comp != null) {
6190            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6191            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
6192            if (pi != null) {
6193                final ResolveInfo ri = new ResolveInfo();
6194                ri.providerInfo = pi;
6195                list.add(ri);
6196            }
6197            return list;
6198        }
6199
6200        // reader
6201        synchronized (mPackages) {
6202            String pkgName = intent.getPackage();
6203            if (pkgName == null) {
6204                return mProviders.queryIntent(intent, resolvedType, flags, userId);
6205            }
6206            final PackageParser.Package pkg = mPackages.get(pkgName);
6207            if (pkg != null) {
6208                return mProviders.queryIntentForPackage(
6209                        intent, resolvedType, flags, pkg.providers, userId);
6210            }
6211            return Collections.emptyList();
6212        }
6213    }
6214
6215    @Override
6216    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
6217        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6218        flags = updateFlagsForPackage(flags, userId, null);
6219        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6220        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6221                true /* requireFullPermission */, false /* checkShell */,
6222                "get installed packages");
6223
6224        // writer
6225        synchronized (mPackages) {
6226            ArrayList<PackageInfo> list;
6227            if (listUninstalled) {
6228                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
6229                for (PackageSetting ps : mSettings.mPackages.values()) {
6230                    final PackageInfo pi;
6231                    if (ps.pkg != null) {
6232                        pi = generatePackageInfo(ps, flags, userId);
6233                    } else {
6234                        pi = generatePackageInfo(ps, flags, userId);
6235                    }
6236                    if (pi != null) {
6237                        list.add(pi);
6238                    }
6239                }
6240            } else {
6241                list = new ArrayList<PackageInfo>(mPackages.size());
6242                for (PackageParser.Package p : mPackages.values()) {
6243                    final PackageInfo pi =
6244                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
6245                    if (pi != null) {
6246                        list.add(pi);
6247                    }
6248                }
6249            }
6250
6251            return new ParceledListSlice<PackageInfo>(list);
6252        }
6253    }
6254
6255    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
6256            String[] permissions, boolean[] tmp, int flags, int userId) {
6257        int numMatch = 0;
6258        final PermissionsState permissionsState = ps.getPermissionsState();
6259        for (int i=0; i<permissions.length; i++) {
6260            final String permission = permissions[i];
6261            if (permissionsState.hasPermission(permission, userId)) {
6262                tmp[i] = true;
6263                numMatch++;
6264            } else {
6265                tmp[i] = false;
6266            }
6267        }
6268        if (numMatch == 0) {
6269            return;
6270        }
6271        final PackageInfo pi;
6272        if (ps.pkg != null) {
6273            pi = generatePackageInfo(ps, flags, userId);
6274        } else {
6275            pi = generatePackageInfo(ps, flags, userId);
6276        }
6277        // The above might return null in cases of uninstalled apps or install-state
6278        // skew across users/profiles.
6279        if (pi != null) {
6280            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6281                if (numMatch == permissions.length) {
6282                    pi.requestedPermissions = permissions;
6283                } else {
6284                    pi.requestedPermissions = new String[numMatch];
6285                    numMatch = 0;
6286                    for (int i=0; i<permissions.length; i++) {
6287                        if (tmp[i]) {
6288                            pi.requestedPermissions[numMatch] = permissions[i];
6289                            numMatch++;
6290                        }
6291                    }
6292                }
6293            }
6294            list.add(pi);
6295        }
6296    }
6297
6298    @Override
6299    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6300            String[] permissions, int flags, int userId) {
6301        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6302        flags = updateFlagsForPackage(flags, userId, permissions);
6303        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6304
6305        // writer
6306        synchronized (mPackages) {
6307            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6308            boolean[] tmpBools = new boolean[permissions.length];
6309            if (listUninstalled) {
6310                for (PackageSetting ps : mSettings.mPackages.values()) {
6311                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6312                }
6313            } else {
6314                for (PackageParser.Package pkg : mPackages.values()) {
6315                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6316                    if (ps != null) {
6317                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6318                                userId);
6319                    }
6320                }
6321            }
6322
6323            return new ParceledListSlice<PackageInfo>(list);
6324        }
6325    }
6326
6327    @Override
6328    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6329        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6330        flags = updateFlagsForApplication(flags, userId, null);
6331        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6332
6333        // writer
6334        synchronized (mPackages) {
6335            ArrayList<ApplicationInfo> list;
6336            if (listUninstalled) {
6337                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6338                for (PackageSetting ps : mSettings.mPackages.values()) {
6339                    ApplicationInfo ai;
6340                    if (ps.pkg != null) {
6341                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6342                                ps.readUserState(userId), userId);
6343                    } else {
6344                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6345                    }
6346                    if (ai != null) {
6347                        list.add(ai);
6348                    }
6349                }
6350            } else {
6351                list = new ArrayList<ApplicationInfo>(mPackages.size());
6352                for (PackageParser.Package p : mPackages.values()) {
6353                    if (p.mExtras != null) {
6354                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6355                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6356                        if (ai != null) {
6357                            list.add(ai);
6358                        }
6359                    }
6360                }
6361            }
6362
6363            return new ParceledListSlice<ApplicationInfo>(list);
6364        }
6365    }
6366
6367    @Override
6368    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6369        if (DISABLE_EPHEMERAL_APPS) {
6370            return null;
6371        }
6372
6373        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6374                "getEphemeralApplications");
6375        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6376                true /* requireFullPermission */, false /* checkShell */,
6377                "getEphemeralApplications");
6378        synchronized (mPackages) {
6379            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6380                    .getEphemeralApplicationsLPw(userId);
6381            if (ephemeralApps != null) {
6382                return new ParceledListSlice<>(ephemeralApps);
6383            }
6384        }
6385        return null;
6386    }
6387
6388    @Override
6389    public boolean isEphemeralApplication(String packageName, int userId) {
6390        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6391                true /* requireFullPermission */, false /* checkShell */,
6392                "isEphemeral");
6393        if (DISABLE_EPHEMERAL_APPS) {
6394            return false;
6395        }
6396
6397        if (!isCallerSameApp(packageName)) {
6398            return false;
6399        }
6400        synchronized (mPackages) {
6401            PackageParser.Package pkg = mPackages.get(packageName);
6402            if (pkg != null) {
6403                return pkg.applicationInfo.isEphemeralApp();
6404            }
6405        }
6406        return false;
6407    }
6408
6409    @Override
6410    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6411        if (DISABLE_EPHEMERAL_APPS) {
6412            return null;
6413        }
6414
6415        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6416                true /* requireFullPermission */, false /* checkShell */,
6417                "getCookie");
6418        if (!isCallerSameApp(packageName)) {
6419            return null;
6420        }
6421        synchronized (mPackages) {
6422            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6423                    packageName, userId);
6424        }
6425    }
6426
6427    @Override
6428    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6429        if (DISABLE_EPHEMERAL_APPS) {
6430            return true;
6431        }
6432
6433        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6434                true /* requireFullPermission */, true /* checkShell */,
6435                "setCookie");
6436        if (!isCallerSameApp(packageName)) {
6437            return false;
6438        }
6439        synchronized (mPackages) {
6440            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6441                    packageName, cookie, userId);
6442        }
6443    }
6444
6445    @Override
6446    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6447        if (DISABLE_EPHEMERAL_APPS) {
6448            return null;
6449        }
6450
6451        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6452                "getEphemeralApplicationIcon");
6453        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6454                true /* requireFullPermission */, false /* checkShell */,
6455                "getEphemeralApplicationIcon");
6456        synchronized (mPackages) {
6457            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6458                    packageName, userId);
6459        }
6460    }
6461
6462    private boolean isCallerSameApp(String packageName) {
6463        PackageParser.Package pkg = mPackages.get(packageName);
6464        return pkg != null
6465                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6466    }
6467
6468    @Override
6469    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6470        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6471    }
6472
6473    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6474        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6475
6476        // reader
6477        synchronized (mPackages) {
6478            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6479            final int userId = UserHandle.getCallingUserId();
6480            while (i.hasNext()) {
6481                final PackageParser.Package p = i.next();
6482                if (p.applicationInfo == null) continue;
6483
6484                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6485                        && !p.applicationInfo.isDirectBootAware();
6486                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6487                        && p.applicationInfo.isDirectBootAware();
6488
6489                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6490                        && (!mSafeMode || isSystemApp(p))
6491                        && (matchesUnaware || matchesAware)) {
6492                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6493                    if (ps != null) {
6494                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6495                                ps.readUserState(userId), userId);
6496                        if (ai != null) {
6497                            finalList.add(ai);
6498                        }
6499                    }
6500                }
6501            }
6502        }
6503
6504        return finalList;
6505    }
6506
6507    @Override
6508    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6509        if (!sUserManager.exists(userId)) return null;
6510        flags = updateFlagsForComponent(flags, userId, name);
6511        // reader
6512        synchronized (mPackages) {
6513            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6514            PackageSetting ps = provider != null
6515                    ? mSettings.mPackages.get(provider.owner.packageName)
6516                    : null;
6517            return ps != null
6518                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6519                    ? PackageParser.generateProviderInfo(provider, flags,
6520                            ps.readUserState(userId), userId)
6521                    : null;
6522        }
6523    }
6524
6525    /**
6526     * @deprecated
6527     */
6528    @Deprecated
6529    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6530        // reader
6531        synchronized (mPackages) {
6532            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6533                    .entrySet().iterator();
6534            final int userId = UserHandle.getCallingUserId();
6535            while (i.hasNext()) {
6536                Map.Entry<String, PackageParser.Provider> entry = i.next();
6537                PackageParser.Provider p = entry.getValue();
6538                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6539
6540                if (ps != null && p.syncable
6541                        && (!mSafeMode || (p.info.applicationInfo.flags
6542                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6543                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6544                            ps.readUserState(userId), userId);
6545                    if (info != null) {
6546                        outNames.add(entry.getKey());
6547                        outInfo.add(info);
6548                    }
6549                }
6550            }
6551        }
6552    }
6553
6554    @Override
6555    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6556            int uid, int flags) {
6557        final int userId = processName != null ? UserHandle.getUserId(uid)
6558                : UserHandle.getCallingUserId();
6559        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6560        flags = updateFlagsForComponent(flags, userId, processName);
6561
6562        ArrayList<ProviderInfo> finalList = null;
6563        // reader
6564        synchronized (mPackages) {
6565            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6566            while (i.hasNext()) {
6567                final PackageParser.Provider p = i.next();
6568                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6569                if (ps != null && p.info.authority != null
6570                        && (processName == null
6571                                || (p.info.processName.equals(processName)
6572                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6573                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6574                    if (finalList == null) {
6575                        finalList = new ArrayList<ProviderInfo>(3);
6576                    }
6577                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6578                            ps.readUserState(userId), userId);
6579                    if (info != null) {
6580                        finalList.add(info);
6581                    }
6582                }
6583            }
6584        }
6585
6586        if (finalList != null) {
6587            Collections.sort(finalList, mProviderInitOrderSorter);
6588            return new ParceledListSlice<ProviderInfo>(finalList);
6589        }
6590
6591        return ParceledListSlice.emptyList();
6592    }
6593
6594    @Override
6595    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6596        // reader
6597        synchronized (mPackages) {
6598            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6599            return PackageParser.generateInstrumentationInfo(i, flags);
6600        }
6601    }
6602
6603    @Override
6604    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6605            String targetPackage, int flags) {
6606        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6607    }
6608
6609    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6610            int flags) {
6611        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6612
6613        // reader
6614        synchronized (mPackages) {
6615            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6616            while (i.hasNext()) {
6617                final PackageParser.Instrumentation p = i.next();
6618                if (targetPackage == null
6619                        || targetPackage.equals(p.info.targetPackage)) {
6620                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6621                            flags);
6622                    if (ii != null) {
6623                        finalList.add(ii);
6624                    }
6625                }
6626            }
6627        }
6628
6629        return finalList;
6630    }
6631
6632    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6633        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6634        if (overlays == null) {
6635            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6636            return;
6637        }
6638        for (PackageParser.Package opkg : overlays.values()) {
6639            // Not much to do if idmap fails: we already logged the error
6640            // and we certainly don't want to abort installation of pkg simply
6641            // because an overlay didn't fit properly. For these reasons,
6642            // ignore the return value of createIdmapForPackagePairLI.
6643            createIdmapForPackagePairLI(pkg, opkg);
6644        }
6645    }
6646
6647    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6648            PackageParser.Package opkg) {
6649        if (!opkg.mTrustedOverlay) {
6650            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6651                    opkg.baseCodePath + ": overlay not trusted");
6652            return false;
6653        }
6654        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6655        if (overlaySet == null) {
6656            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6657                    opkg.baseCodePath + " but target package has no known overlays");
6658            return false;
6659        }
6660        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6661        // TODO: generate idmap for split APKs
6662        try {
6663            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6664        } catch (InstallerException e) {
6665            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6666                    + opkg.baseCodePath);
6667            return false;
6668        }
6669        PackageParser.Package[] overlayArray =
6670            overlaySet.values().toArray(new PackageParser.Package[0]);
6671        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6672            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6673                return p1.mOverlayPriority - p2.mOverlayPriority;
6674            }
6675        };
6676        Arrays.sort(overlayArray, cmp);
6677
6678        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6679        int i = 0;
6680        for (PackageParser.Package p : overlayArray) {
6681            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6682        }
6683        return true;
6684    }
6685
6686    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6687        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6688        try {
6689            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6690        } finally {
6691            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6692        }
6693    }
6694
6695    private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
6696        final File[] files = dir.listFiles();
6697        if (ArrayUtils.isEmpty(files)) {
6698            Log.d(TAG, "No files in app dir " + dir);
6699            return;
6700        }
6701
6702        if (DEBUG_PACKAGE_SCANNING) {
6703            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6704                    + " flags=0x" + Integer.toHexString(parseFlags));
6705        }
6706
6707        for (File file : files) {
6708            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6709                    && !PackageInstallerService.isStageName(file.getName());
6710            if (!isPackage) {
6711                // Ignore entries which are not packages
6712                continue;
6713            }
6714            try {
6715                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6716                        scanFlags, currentTime, null);
6717            } catch (PackageManagerException e) {
6718                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6719
6720                // Delete invalid userdata apps
6721                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6722                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6723                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6724                    removeCodePathLI(file);
6725                }
6726            }
6727        }
6728    }
6729
6730    private static File getSettingsProblemFile() {
6731        File dataDir = Environment.getDataDirectory();
6732        File systemDir = new File(dataDir, "system");
6733        File fname = new File(systemDir, "uiderrors.txt");
6734        return fname;
6735    }
6736
6737    static void reportSettingsProblem(int priority, String msg) {
6738        logCriticalInfo(priority, msg);
6739    }
6740
6741    static void logCriticalInfo(int priority, String msg) {
6742        Slog.println(priority, TAG, msg);
6743        EventLogTags.writePmCriticalInfo(msg);
6744        try {
6745            File fname = getSettingsProblemFile();
6746            FileOutputStream out = new FileOutputStream(fname, true);
6747            PrintWriter pw = new FastPrintWriter(out);
6748            SimpleDateFormat formatter = new SimpleDateFormat();
6749            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6750            pw.println(dateString + ": " + msg);
6751            pw.close();
6752            FileUtils.setPermissions(
6753                    fname.toString(),
6754                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6755                    -1, -1);
6756        } catch (java.io.IOException e) {
6757        }
6758    }
6759
6760    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6761            final int policyFlags) throws PackageManagerException {
6762        if (ps != null
6763                && ps.codePath.equals(srcFile)
6764                && ps.timeStamp == srcFile.lastModified()
6765                && !isCompatSignatureUpdateNeeded(pkg)
6766                && !isRecoverSignatureUpdateNeeded(pkg)) {
6767            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6768            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6769            ArraySet<PublicKey> signingKs;
6770            synchronized (mPackages) {
6771                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6772            }
6773            if (ps.signatures.mSignatures != null
6774                    && ps.signatures.mSignatures.length != 0
6775                    && signingKs != null) {
6776                // Optimization: reuse the existing cached certificates
6777                // if the package appears to be unchanged.
6778                pkg.mSignatures = ps.signatures.mSignatures;
6779                pkg.mSigningKeys = signingKs;
6780                return;
6781            }
6782
6783            Slog.w(TAG, "PackageSetting for " + ps.name
6784                    + " is missing signatures.  Collecting certs again to recover them.");
6785        } else {
6786            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6787        }
6788
6789        try {
6790            PackageParser.collectCertificates(pkg, policyFlags);
6791        } catch (PackageParserException e) {
6792            throw PackageManagerException.from(e);
6793        }
6794    }
6795
6796    /**
6797     *  Traces a package scan.
6798     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6799     */
6800    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
6801            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6802        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6803        try {
6804            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6805        } finally {
6806            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6807        }
6808    }
6809
6810    /**
6811     *  Scans a package and returns the newly parsed package.
6812     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6813     */
6814    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6815            long currentTime, UserHandle user) throws PackageManagerException {
6816        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6817        PackageParser pp = new PackageParser();
6818        pp.setSeparateProcesses(mSeparateProcesses);
6819        pp.setOnlyCoreApps(mOnlyCore);
6820        pp.setDisplayMetrics(mMetrics);
6821
6822        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6823            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6824        }
6825
6826        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
6827        final PackageParser.Package pkg;
6828        try {
6829            pkg = pp.parsePackage(scanFile, parseFlags);
6830        } catch (PackageParserException e) {
6831            throw PackageManagerException.from(e);
6832        } finally {
6833            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6834        }
6835
6836        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6837    }
6838
6839    /**
6840     *  Scans a package and returns the newly parsed package.
6841     *  @throws PackageManagerException on a parse error.
6842     */
6843    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6844            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
6845            throws PackageManagerException {
6846        // If the package has children and this is the first dive in the function
6847        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6848        // packages (parent and children) would be successfully scanned before the
6849        // actual scan since scanning mutates internal state and we want to atomically
6850        // install the package and its children.
6851        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6852            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6853                scanFlags |= SCAN_CHECK_ONLY;
6854            }
6855        } else {
6856            scanFlags &= ~SCAN_CHECK_ONLY;
6857        }
6858
6859        // Scan the parent
6860        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
6861                scanFlags, currentTime, user);
6862
6863        // Scan the children
6864        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6865        for (int i = 0; i < childCount; i++) {
6866            PackageParser.Package childPackage = pkg.childPackages.get(i);
6867            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
6868                    currentTime, user);
6869        }
6870
6871
6872        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6873            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
6874        }
6875
6876        return scannedPkg;
6877    }
6878
6879    /**
6880     *  Scans a package and returns the newly parsed package.
6881     *  @throws PackageManagerException on a parse error.
6882     */
6883    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6884            int policyFlags, int scanFlags, long currentTime, UserHandle user)
6885            throws PackageManagerException {
6886        PackageSetting ps = null;
6887        PackageSetting updatedPkg;
6888        // reader
6889        synchronized (mPackages) {
6890            // Look to see if we already know about this package.
6891            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6892            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6893                // This package has been renamed to its original name.  Let's
6894                // use that.
6895                ps = mSettings.peekPackageLPr(oldName);
6896            }
6897            // If there was no original package, see one for the real package name.
6898            if (ps == null) {
6899                ps = mSettings.peekPackageLPr(pkg.packageName);
6900            }
6901            // Check to see if this package could be hiding/updating a system
6902            // package.  Must look for it either under the original or real
6903            // package name depending on our state.
6904            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6905            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6906
6907            // If this is a package we don't know about on the system partition, we
6908            // may need to remove disabled child packages on the system partition
6909            // or may need to not add child packages if the parent apk is updated
6910            // on the data partition and no longer defines this child package.
6911            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6912                // If this is a parent package for an updated system app and this system
6913                // app got an OTA update which no longer defines some of the child packages
6914                // we have to prune them from the disabled system packages.
6915                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6916                if (disabledPs != null) {
6917                    final int scannedChildCount = (pkg.childPackages != null)
6918                            ? pkg.childPackages.size() : 0;
6919                    final int disabledChildCount = disabledPs.childPackageNames != null
6920                            ? disabledPs.childPackageNames.size() : 0;
6921                    for (int i = 0; i < disabledChildCount; i++) {
6922                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6923                        boolean disabledPackageAvailable = false;
6924                        for (int j = 0; j < scannedChildCount; j++) {
6925                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6926                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6927                                disabledPackageAvailable = true;
6928                                break;
6929                            }
6930                         }
6931                         if (!disabledPackageAvailable) {
6932                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6933                         }
6934                    }
6935                }
6936            }
6937        }
6938
6939        boolean updatedPkgBetter = false;
6940        // First check if this is a system package that may involve an update
6941        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6942            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6943            // it needs to drop FLAG_PRIVILEGED.
6944            if (locationIsPrivileged(scanFile)) {
6945                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6946            } else {
6947                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6948            }
6949
6950            if (ps != null && !ps.codePath.equals(scanFile)) {
6951                // The path has changed from what was last scanned...  check the
6952                // version of the new path against what we have stored to determine
6953                // what to do.
6954                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6955                if (pkg.mVersionCode <= ps.versionCode) {
6956                    // The system package has been updated and the code path does not match
6957                    // Ignore entry. Skip it.
6958                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6959                            + " ignored: updated version " + ps.versionCode
6960                            + " better than this " + pkg.mVersionCode);
6961                    if (!updatedPkg.codePath.equals(scanFile)) {
6962                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6963                                + ps.name + " changing from " + updatedPkg.codePathString
6964                                + " to " + scanFile);
6965                        updatedPkg.codePath = scanFile;
6966                        updatedPkg.codePathString = scanFile.toString();
6967                        updatedPkg.resourcePath = scanFile;
6968                        updatedPkg.resourcePathString = scanFile.toString();
6969                    }
6970                    updatedPkg.pkg = pkg;
6971                    updatedPkg.versionCode = pkg.mVersionCode;
6972
6973                    // Update the disabled system child packages to point to the package too.
6974                    final int childCount = updatedPkg.childPackageNames != null
6975                            ? updatedPkg.childPackageNames.size() : 0;
6976                    for (int i = 0; i < childCount; i++) {
6977                        String childPackageName = updatedPkg.childPackageNames.get(i);
6978                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6979                                childPackageName);
6980                        if (updatedChildPkg != null) {
6981                            updatedChildPkg.pkg = pkg;
6982                            updatedChildPkg.versionCode = pkg.mVersionCode;
6983                        }
6984                    }
6985
6986                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6987                            + scanFile + " ignored: updated version " + ps.versionCode
6988                            + " better than this " + pkg.mVersionCode);
6989                } else {
6990                    // The current app on the system partition is better than
6991                    // what we have updated to on the data partition; switch
6992                    // back to the system partition version.
6993                    // At this point, its safely assumed that package installation for
6994                    // apps in system partition will go through. If not there won't be a working
6995                    // version of the app
6996                    // writer
6997                    synchronized (mPackages) {
6998                        // Just remove the loaded entries from package lists.
6999                        mPackages.remove(ps.name);
7000                    }
7001
7002                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7003                            + " reverting from " + ps.codePathString
7004                            + ": new version " + pkg.mVersionCode
7005                            + " better than installed " + ps.versionCode);
7006
7007                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7008                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7009                    synchronized (mInstallLock) {
7010                        args.cleanUpResourcesLI();
7011                    }
7012                    synchronized (mPackages) {
7013                        mSettings.enableSystemPackageLPw(ps.name);
7014                    }
7015                    updatedPkgBetter = true;
7016                }
7017            }
7018        }
7019
7020        if (updatedPkg != null) {
7021            // An updated system app will not have the PARSE_IS_SYSTEM flag set
7022            // initially
7023            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
7024
7025            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
7026            // flag set initially
7027            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
7028                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
7029            }
7030        }
7031
7032        // Verify certificates against what was last scanned
7033        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
7034
7035        /*
7036         * A new system app appeared, but we already had a non-system one of the
7037         * same name installed earlier.
7038         */
7039        boolean shouldHideSystemApp = false;
7040        if (updatedPkg == null && ps != null
7041                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
7042            /*
7043             * Check to make sure the signatures match first. If they don't,
7044             * wipe the installed application and its data.
7045             */
7046            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
7047                    != PackageManager.SIGNATURE_MATCH) {
7048                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
7049                        + " signatures don't match existing userdata copy; removing");
7050                try (PackageFreezer freezer = freezePackage(pkg.packageName,
7051                        "scanPackageInternalLI")) {
7052                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
7053                }
7054                ps = null;
7055            } else {
7056                /*
7057                 * If the newly-added system app is an older version than the
7058                 * already installed version, hide it. It will be scanned later
7059                 * and re-added like an update.
7060                 */
7061                if (pkg.mVersionCode <= ps.versionCode) {
7062                    shouldHideSystemApp = true;
7063                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
7064                            + " but new version " + pkg.mVersionCode + " better than installed "
7065                            + ps.versionCode + "; hiding system");
7066                } else {
7067                    /*
7068                     * The newly found system app is a newer version that the
7069                     * one previously installed. Simply remove the
7070                     * already-installed application and replace it with our own
7071                     * while keeping the application data.
7072                     */
7073                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
7074                            + " reverting from " + ps.codePathString + ": new version "
7075                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
7076                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
7077                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
7078                    synchronized (mInstallLock) {
7079                        args.cleanUpResourcesLI();
7080                    }
7081                }
7082            }
7083        }
7084
7085        // The apk is forward locked (not public) if its code and resources
7086        // are kept in different files. (except for app in either system or
7087        // vendor path).
7088        // TODO grab this value from PackageSettings
7089        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7090            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
7091                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
7092            }
7093        }
7094
7095        // TODO: extend to support forward-locked splits
7096        String resourcePath = null;
7097        String baseResourcePath = null;
7098        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
7099            if (ps != null && ps.resourcePathString != null) {
7100                resourcePath = ps.resourcePathString;
7101                baseResourcePath = ps.resourcePathString;
7102            } else {
7103                // Should not happen at all. Just log an error.
7104                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
7105            }
7106        } else {
7107            resourcePath = pkg.codePath;
7108            baseResourcePath = pkg.baseCodePath;
7109        }
7110
7111        // Set application objects path explicitly.
7112        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
7113        pkg.setApplicationInfoCodePath(pkg.codePath);
7114        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
7115        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
7116        pkg.setApplicationInfoResourcePath(resourcePath);
7117        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
7118        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
7119
7120        // Note that we invoke the following method only if we are about to unpack an application
7121        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
7122                | SCAN_UPDATE_SIGNATURE, currentTime, user);
7123
7124        /*
7125         * If the system app should be overridden by a previously installed
7126         * data, hide the system app now and let the /data/app scan pick it up
7127         * again.
7128         */
7129        if (shouldHideSystemApp) {
7130            synchronized (mPackages) {
7131                mSettings.disableSystemPackageLPw(pkg.packageName, true);
7132            }
7133        }
7134
7135        return scannedPkg;
7136    }
7137
7138    private static String fixProcessName(String defProcessName,
7139            String processName, int uid) {
7140        if (processName == null) {
7141            return defProcessName;
7142        }
7143        return processName;
7144    }
7145
7146    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
7147            throws PackageManagerException {
7148        if (pkgSetting.signatures.mSignatures != null) {
7149            // Already existing package. Make sure signatures match
7150            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
7151                    == PackageManager.SIGNATURE_MATCH;
7152            if (!match) {
7153                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
7154                        == PackageManager.SIGNATURE_MATCH;
7155            }
7156            if (!match) {
7157                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
7158                        == PackageManager.SIGNATURE_MATCH;
7159            }
7160            if (!match) {
7161                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
7162                        + pkg.packageName + " signatures do not match the "
7163                        + "previously installed version; ignoring!");
7164            }
7165        }
7166
7167        // Check for shared user signatures
7168        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
7169            // Already existing package. Make sure signatures match
7170            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7171                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
7172            if (!match) {
7173                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
7174                        == PackageManager.SIGNATURE_MATCH;
7175            }
7176            if (!match) {
7177                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
7178                        == PackageManager.SIGNATURE_MATCH;
7179            }
7180            if (!match) {
7181                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
7182                        "Package " + pkg.packageName
7183                        + " has no signatures that match those in shared user "
7184                        + pkgSetting.sharedUser.name + "; ignoring!");
7185            }
7186        }
7187    }
7188
7189    /**
7190     * Enforces that only the system UID or root's UID can call a method exposed
7191     * via Binder.
7192     *
7193     * @param message used as message if SecurityException is thrown
7194     * @throws SecurityException if the caller is not system or root
7195     */
7196    private static final void enforceSystemOrRoot(String message) {
7197        final int uid = Binder.getCallingUid();
7198        if (uid != Process.SYSTEM_UID && uid != 0) {
7199            throw new SecurityException(message);
7200        }
7201    }
7202
7203    @Override
7204    public void performFstrimIfNeeded() {
7205        enforceSystemOrRoot("Only the system can request fstrim");
7206
7207        // Before everything else, see whether we need to fstrim.
7208        try {
7209            IMountService ms = PackageHelper.getMountService();
7210            if (ms != null) {
7211                final boolean isUpgrade = isUpgrade();
7212                boolean doTrim = isUpgrade;
7213                if (doTrim) {
7214                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
7215                } else {
7216                    final long interval = android.provider.Settings.Global.getLong(
7217                            mContext.getContentResolver(),
7218                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
7219                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
7220                    if (interval > 0) {
7221                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
7222                        if (timeSinceLast > interval) {
7223                            doTrim = true;
7224                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
7225                                    + "; running immediately");
7226                        }
7227                    }
7228                }
7229                if (doTrim) {
7230                    if (!isFirstBoot()) {
7231                        try {
7232                            ActivityManagerNative.getDefault().showBootMessage(
7233                                    mContext.getResources().getString(
7234                                            R.string.android_upgrading_fstrim), true);
7235                        } catch (RemoteException e) {
7236                        }
7237                    }
7238                    ms.runMaintenance();
7239                }
7240            } else {
7241                Slog.e(TAG, "Mount service unavailable!");
7242            }
7243        } catch (RemoteException e) {
7244            // Can't happen; MountService is local
7245        }
7246    }
7247
7248    @Override
7249    public void updatePackagesIfNeeded() {
7250        enforceSystemOrRoot("Only the system can request package update");
7251
7252        // We need to re-extract after an OTA.
7253        boolean causeUpgrade = isUpgrade();
7254
7255        // First boot or factory reset.
7256        // Note: we also handle devices that are upgrading to N right now as if it is their
7257        //       first boot, as they do not have profile data.
7258        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
7259
7260        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
7261        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
7262
7263        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7264            return;
7265        }
7266
7267        List<PackageParser.Package> pkgs;
7268        synchronized (mPackages) {
7269            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7270        }
7271
7272        final long startTime = System.nanoTime();
7273        final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */,
7274                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
7275
7276        final int elapsedTimeSeconds =
7277                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
7278
7279        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
7280        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
7281        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
7282        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
7283        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
7284    }
7285
7286    /**
7287     * Performs dexopt on the set of packages in {@code packages} and returns an int array
7288     * containing statistics about the invocation. The array consists of three elements,
7289     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
7290     * and {@code numberOfPackagesFailed}.
7291     */
7292    private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog,
7293            String compilerFilter) {
7294
7295        int numberOfPackagesVisited = 0;
7296        int numberOfPackagesOptimized = 0;
7297        int numberOfPackagesSkipped = 0;
7298        int numberOfPackagesFailed = 0;
7299        final int numberOfPackagesToDexopt = pkgs.size();
7300
7301        for (PackageParser.Package pkg : pkgs) {
7302            numberOfPackagesVisited++;
7303
7304            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
7305                if (DEBUG_DEXOPT) {
7306                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
7307                }
7308                numberOfPackagesSkipped++;
7309                continue;
7310            }
7311
7312            if (DEBUG_DEXOPT) {
7313                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
7314                        numberOfPackagesToDexopt + ": " + pkg.packageName);
7315            }
7316
7317            if (showDialog) {
7318                try {
7319                    ActivityManagerNative.getDefault().showBootMessage(
7320                            mContext.getResources().getString(R.string.android_upgrading_apk,
7321                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
7322                } catch (RemoteException e) {
7323                }
7324            }
7325
7326            // checkProfiles is false to avoid merging profiles during boot which
7327            // might interfere with background compilation (b/28612421).
7328            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
7329            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
7330            // trade-off worth doing to save boot time work.
7331            int dexOptStatus = performDexOptTraced(pkg.packageName,
7332                    false /* checkProfiles */,
7333                    compilerFilter,
7334                    false /* force */);
7335            switch (dexOptStatus) {
7336                case PackageDexOptimizer.DEX_OPT_PERFORMED:
7337                    numberOfPackagesOptimized++;
7338                    break;
7339                case PackageDexOptimizer.DEX_OPT_SKIPPED:
7340                    numberOfPackagesSkipped++;
7341                    break;
7342                case PackageDexOptimizer.DEX_OPT_FAILED:
7343                    numberOfPackagesFailed++;
7344                    break;
7345                default:
7346                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
7347                    break;
7348            }
7349        }
7350
7351        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
7352                numberOfPackagesFailed };
7353    }
7354
7355    @Override
7356    public void notifyPackageUse(String packageName, int reason) {
7357        synchronized (mPackages) {
7358            PackageParser.Package p = mPackages.get(packageName);
7359            if (p == null) {
7360                return;
7361            }
7362            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
7363        }
7364    }
7365
7366    // TODO: this is not used nor needed. Delete it.
7367    @Override
7368    public boolean performDexOptIfNeeded(String packageName) {
7369        int dexOptStatus = performDexOptTraced(packageName,
7370                false /* checkProfiles */, getFullCompilerFilter(), false /* force */);
7371        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7372    }
7373
7374    @Override
7375    public boolean performDexOpt(String packageName,
7376            boolean checkProfiles, int compileReason, boolean force) {
7377        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7378                getCompilerFilterForReason(compileReason), force);
7379        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7380    }
7381
7382    @Override
7383    public boolean performDexOptMode(String packageName,
7384            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7385        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
7386                targetCompilerFilter, force);
7387        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
7388    }
7389
7390    private int performDexOptTraced(String packageName,
7391                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7392        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7393        try {
7394            return performDexOptInternal(packageName, checkProfiles,
7395                    targetCompilerFilter, force);
7396        } finally {
7397            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7398        }
7399    }
7400
7401    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
7402    // if the package can now be considered up to date for the given filter.
7403    private int performDexOptInternal(String packageName,
7404                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7405        PackageParser.Package p;
7406        synchronized (mPackages) {
7407            p = mPackages.get(packageName);
7408            if (p == null) {
7409                // Package could not be found. Report failure.
7410                return PackageDexOptimizer.DEX_OPT_FAILED;
7411            }
7412            mPackageUsage.write(false);
7413        }
7414        long callingId = Binder.clearCallingIdentity();
7415        try {
7416            synchronized (mInstallLock) {
7417                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
7418                        targetCompilerFilter, force);
7419            }
7420        } finally {
7421            Binder.restoreCallingIdentity(callingId);
7422        }
7423    }
7424
7425    public ArraySet<String> getOptimizablePackages() {
7426        ArraySet<String> pkgs = new ArraySet<String>();
7427        synchronized (mPackages) {
7428            for (PackageParser.Package p : mPackages.values()) {
7429                if (PackageDexOptimizer.canOptimizePackage(p)) {
7430                    pkgs.add(p.packageName);
7431                }
7432            }
7433        }
7434        return pkgs;
7435    }
7436
7437    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7438            boolean checkProfiles, String targetCompilerFilter,
7439            boolean force) {
7440        // Select the dex optimizer based on the force parameter.
7441        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7442        //       allocate an object here.
7443        PackageDexOptimizer pdo = force
7444                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7445                : mPackageDexOptimizer;
7446
7447        // Optimize all dependencies first. Note: we ignore the return value and march on
7448        // on errors.
7449        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7450        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
7451        if (!deps.isEmpty()) {
7452            for (PackageParser.Package depPackage : deps) {
7453                // TODO: Analyze and investigate if we (should) profile libraries.
7454                // Currently this will do a full compilation of the library by default.
7455                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
7456                        false /* checkProfiles */,
7457                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7458            }
7459        }
7460        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
7461                targetCompilerFilter);
7462    }
7463
7464    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7465        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7466            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7467            Set<String> collectedNames = new HashSet<>();
7468            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7469
7470            retValue.remove(p);
7471
7472            return retValue;
7473        } else {
7474            return Collections.emptyList();
7475        }
7476    }
7477
7478    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7479            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7480        if (!collectedNames.contains(p.packageName)) {
7481            collectedNames.add(p.packageName);
7482            collected.add(p);
7483
7484            if (p.usesLibraries != null) {
7485                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7486            }
7487            if (p.usesOptionalLibraries != null) {
7488                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7489                        collectedNames);
7490            }
7491        }
7492    }
7493
7494    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7495            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7496        for (String libName : libs) {
7497            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7498            if (libPkg != null) {
7499                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7500            }
7501        }
7502    }
7503
7504    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7505        synchronized (mPackages) {
7506            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7507            if (lib != null && lib.apk != null) {
7508                return mPackages.get(lib.apk);
7509            }
7510        }
7511        return null;
7512    }
7513
7514    public void shutdown() {
7515        mPackageUsage.write(true);
7516    }
7517
7518    @Override
7519    public void dumpProfiles(String packageName) {
7520        PackageParser.Package pkg;
7521        synchronized (mPackages) {
7522            pkg = mPackages.get(packageName);
7523            if (pkg == null) {
7524                throw new IllegalArgumentException("Unknown package: " + packageName);
7525            }
7526        }
7527        /* Only the shell, root, or the app user should be able to dump profiles. */
7528        int callingUid = Binder.getCallingUid();
7529        if (callingUid != Process.SHELL_UID &&
7530            callingUid != Process.ROOT_UID &&
7531            callingUid != pkg.applicationInfo.uid) {
7532            throw new SecurityException("dumpProfiles");
7533        }
7534
7535        synchronized (mInstallLock) {
7536            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
7537            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
7538            try {
7539                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
7540                String gid = Integer.toString(sharedGid);
7541                String codePaths = TextUtils.join(";", allCodePaths);
7542                mInstaller.dumpProfiles(gid, packageName, codePaths);
7543            } catch (InstallerException e) {
7544                Slog.w(TAG, "Failed to dump profiles", e);
7545            }
7546            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7547        }
7548    }
7549
7550    @Override
7551    public void forceDexOpt(String packageName) {
7552        enforceSystemOrRoot("forceDexOpt");
7553
7554        PackageParser.Package pkg;
7555        synchronized (mPackages) {
7556            pkg = mPackages.get(packageName);
7557            if (pkg == null) {
7558                throw new IllegalArgumentException("Unknown package: " + packageName);
7559            }
7560        }
7561
7562        synchronized (mInstallLock) {
7563            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7564
7565            // Whoever is calling forceDexOpt wants a fully compiled package.
7566            // Don't use profiles since that may cause compilation to be skipped.
7567            final int res = performDexOptInternalWithDependenciesLI(pkg,
7568                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7569                    true /* force */);
7570
7571            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7572            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7573                throw new IllegalStateException("Failed to dexopt: " + res);
7574            }
7575        }
7576    }
7577
7578    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7579        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7580            Slog.w(TAG, "Unable to update from " + oldPkg.name
7581                    + " to " + newPkg.packageName
7582                    + ": old package not in system partition");
7583            return false;
7584        } else if (mPackages.get(oldPkg.name) != null) {
7585            Slog.w(TAG, "Unable to update from " + oldPkg.name
7586                    + " to " + newPkg.packageName
7587                    + ": old package still exists");
7588            return false;
7589        }
7590        return true;
7591    }
7592
7593    void removeCodePathLI(File codePath) {
7594        if (codePath.isDirectory()) {
7595            try {
7596                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7597            } catch (InstallerException e) {
7598                Slog.w(TAG, "Failed to remove code path", e);
7599            }
7600        } else {
7601            codePath.delete();
7602        }
7603    }
7604
7605    private int[] resolveUserIds(int userId) {
7606        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
7607    }
7608
7609    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7610        if (pkg == null) {
7611            Slog.wtf(TAG, "Package was null!", new Throwable());
7612            return;
7613        }
7614        clearAppDataLeafLIF(pkg, userId, flags);
7615        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7616        for (int i = 0; i < childCount; i++) {
7617            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7618        }
7619    }
7620
7621    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7622        final PackageSetting ps;
7623        synchronized (mPackages) {
7624            ps = mSettings.mPackages.get(pkg.packageName);
7625        }
7626        for (int realUserId : resolveUserIds(userId)) {
7627            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7628            try {
7629                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7630                        ceDataInode);
7631            } catch (InstallerException e) {
7632                Slog.w(TAG, String.valueOf(e));
7633            }
7634        }
7635    }
7636
7637    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
7638        if (pkg == null) {
7639            Slog.wtf(TAG, "Package was null!", new Throwable());
7640            return;
7641        }
7642        destroyAppDataLeafLIF(pkg, userId, flags);
7643        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7644        for (int i = 0; i < childCount; i++) {
7645            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
7646        }
7647    }
7648
7649    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
7650        final PackageSetting ps;
7651        synchronized (mPackages) {
7652            ps = mSettings.mPackages.get(pkg.packageName);
7653        }
7654        for (int realUserId : resolveUserIds(userId)) {
7655            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
7656            try {
7657                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
7658                        ceDataInode);
7659            } catch (InstallerException e) {
7660                Slog.w(TAG, String.valueOf(e));
7661            }
7662        }
7663    }
7664
7665    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
7666        if (pkg == null) {
7667            Slog.wtf(TAG, "Package was null!", new Throwable());
7668            return;
7669        }
7670        destroyAppProfilesLeafLIF(pkg);
7671        destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */);
7672        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7673        for (int i = 0; i < childCount; i++) {
7674            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
7675            destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId,
7676                    true /* removeBaseMarker */);
7677        }
7678    }
7679
7680    private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId,
7681            boolean removeBaseMarker) {
7682        if (pkg.isForwardLocked()) {
7683            return;
7684        }
7685
7686        for (String path : pkg.getAllCodePathsExcludingResourceOnly()) {
7687            try {
7688                path = PackageManagerServiceUtils.realpath(new File(path));
7689            } catch (IOException e) {
7690                // TODO: Should we return early here ?
7691                Slog.w(TAG, "Failed to get canonical path", e);
7692                continue;
7693            }
7694
7695            final String useMarker = path.replace('/', '@');
7696            for (int realUserId : resolveUserIds(userId)) {
7697                File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId);
7698                if (removeBaseMarker) {
7699                    File foreignUseMark = new File(profileDir, useMarker);
7700                    if (foreignUseMark.exists()) {
7701                        if (!foreignUseMark.delete()) {
7702                            Slog.w(TAG, "Unable to delete foreign user mark for package: "
7703                                    + pkg.packageName);
7704                        }
7705                    }
7706                }
7707
7708                File[] markers = profileDir.listFiles();
7709                if (markers != null) {
7710                    final String searchString = "@" + pkg.packageName + "@";
7711                    // We also delete all markers that contain the package name we're
7712                    // uninstalling. These are associated with secondary dex-files belonging
7713                    // to the package. Reconstructing the path of these dex files is messy
7714                    // in general.
7715                    for (File marker : markers) {
7716                        if (marker.getName().indexOf(searchString) > 0) {
7717                            if (!marker.delete()) {
7718                                Slog.w(TAG, "Unable to delete foreign user mark for package: "
7719                                    + pkg.packageName);
7720                            }
7721                        }
7722                    }
7723                }
7724            }
7725        }
7726    }
7727
7728    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
7729        try {
7730            mInstaller.destroyAppProfiles(pkg.packageName);
7731        } catch (InstallerException e) {
7732            Slog.w(TAG, String.valueOf(e));
7733        }
7734    }
7735
7736    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
7737        if (pkg == null) {
7738            Slog.wtf(TAG, "Package was null!", new Throwable());
7739            return;
7740        }
7741        clearAppProfilesLeafLIF(pkg);
7742        // We don't remove the base foreign use marker when clearing profiles because
7743        // we will rename it when the app is updated. Unlike the actual profile contents,
7744        // the foreign use marker is good across installs.
7745        destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */);
7746        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7747        for (int i = 0; i < childCount; i++) {
7748            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
7749        }
7750    }
7751
7752    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
7753        try {
7754            mInstaller.clearAppProfiles(pkg.packageName);
7755        } catch (InstallerException e) {
7756            Slog.w(TAG, String.valueOf(e));
7757        }
7758    }
7759
7760    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7761            long lastUpdateTime) {
7762        // Set parent install/update time
7763        PackageSetting ps = (PackageSetting) pkg.mExtras;
7764        if (ps != null) {
7765            ps.firstInstallTime = firstInstallTime;
7766            ps.lastUpdateTime = lastUpdateTime;
7767        }
7768        // Set children install/update time
7769        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7770        for (int i = 0; i < childCount; i++) {
7771            PackageParser.Package childPkg = pkg.childPackages.get(i);
7772            ps = (PackageSetting) childPkg.mExtras;
7773            if (ps != null) {
7774                ps.firstInstallTime = firstInstallTime;
7775                ps.lastUpdateTime = lastUpdateTime;
7776            }
7777        }
7778    }
7779
7780    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7781            PackageParser.Package changingLib) {
7782        if (file.path != null) {
7783            usesLibraryFiles.add(file.path);
7784            return;
7785        }
7786        PackageParser.Package p = mPackages.get(file.apk);
7787        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7788            // If we are doing this while in the middle of updating a library apk,
7789            // then we need to make sure to use that new apk for determining the
7790            // dependencies here.  (We haven't yet finished committing the new apk
7791            // to the package manager state.)
7792            if (p == null || p.packageName.equals(changingLib.packageName)) {
7793                p = changingLib;
7794            }
7795        }
7796        if (p != null) {
7797            usesLibraryFiles.addAll(p.getAllCodePaths());
7798        }
7799    }
7800
7801    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7802            PackageParser.Package changingLib) throws PackageManagerException {
7803        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7804            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7805            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7806            for (int i=0; i<N; i++) {
7807                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7808                if (file == null) {
7809                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7810                            "Package " + pkg.packageName + " requires unavailable shared library "
7811                            + pkg.usesLibraries.get(i) + "; failing!");
7812                }
7813                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7814            }
7815            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7816            for (int i=0; i<N; i++) {
7817                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7818                if (file == null) {
7819                    Slog.w(TAG, "Package " + pkg.packageName
7820                            + " desires unavailable shared library "
7821                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7822                } else {
7823                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7824                }
7825            }
7826            N = usesLibraryFiles.size();
7827            if (N > 0) {
7828                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7829            } else {
7830                pkg.usesLibraryFiles = null;
7831            }
7832        }
7833    }
7834
7835    private static boolean hasString(List<String> list, List<String> which) {
7836        if (list == null) {
7837            return false;
7838        }
7839        for (int i=list.size()-1; i>=0; i--) {
7840            for (int j=which.size()-1; j>=0; j--) {
7841                if (which.get(j).equals(list.get(i))) {
7842                    return true;
7843                }
7844            }
7845        }
7846        return false;
7847    }
7848
7849    private void updateAllSharedLibrariesLPw() {
7850        for (PackageParser.Package pkg : mPackages.values()) {
7851            try {
7852                updateSharedLibrariesLPw(pkg, null);
7853            } catch (PackageManagerException e) {
7854                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7855            }
7856        }
7857    }
7858
7859    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7860            PackageParser.Package changingPkg) {
7861        ArrayList<PackageParser.Package> res = null;
7862        for (PackageParser.Package pkg : mPackages.values()) {
7863            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7864                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7865                if (res == null) {
7866                    res = new ArrayList<PackageParser.Package>();
7867                }
7868                res.add(pkg);
7869                try {
7870                    updateSharedLibrariesLPw(pkg, changingPkg);
7871                } catch (PackageManagerException e) {
7872                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7873                }
7874            }
7875        }
7876        return res;
7877    }
7878
7879    /**
7880     * Derive the value of the {@code cpuAbiOverride} based on the provided
7881     * value and an optional stored value from the package settings.
7882     */
7883    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7884        String cpuAbiOverride = null;
7885
7886        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7887            cpuAbiOverride = null;
7888        } else if (abiOverride != null) {
7889            cpuAbiOverride = abiOverride;
7890        } else if (settings != null) {
7891            cpuAbiOverride = settings.cpuAbiOverrideString;
7892        }
7893
7894        return cpuAbiOverride;
7895    }
7896
7897    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
7898            final int policyFlags, int scanFlags, long currentTime, UserHandle user)
7899                    throws PackageManagerException {
7900        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7901        // If the package has children and this is the first dive in the function
7902        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7903        // whether all packages (parent and children) would be successfully scanned
7904        // before the actual scan since scanning mutates internal state and we want
7905        // to atomically install the package and its children.
7906        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7907            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7908                scanFlags |= SCAN_CHECK_ONLY;
7909            }
7910        } else {
7911            scanFlags &= ~SCAN_CHECK_ONLY;
7912        }
7913
7914        final PackageParser.Package scannedPkg;
7915        try {
7916            // Scan the parent
7917            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
7918            // Scan the children
7919            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7920            for (int i = 0; i < childCount; i++) {
7921                PackageParser.Package childPkg = pkg.childPackages.get(i);
7922                scanPackageLI(childPkg, policyFlags,
7923                        scanFlags, currentTime, user);
7924            }
7925        } finally {
7926            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7927        }
7928
7929        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7930            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
7931        }
7932
7933        return scannedPkg;
7934    }
7935
7936    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
7937            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7938        boolean success = false;
7939        try {
7940            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
7941                    currentTime, user);
7942            success = true;
7943            return res;
7944        } finally {
7945            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7946                // DELETE_DATA_ON_FAILURES is only used by frozen paths
7947                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
7948                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
7949                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
7950            }
7951        }
7952    }
7953
7954    /**
7955     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
7956     */
7957    private static boolean apkHasCode(String fileName) {
7958        StrictJarFile jarFile = null;
7959        try {
7960            jarFile = new StrictJarFile(fileName,
7961                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
7962            return jarFile.findEntry("classes.dex") != null;
7963        } catch (IOException ignore) {
7964        } finally {
7965            try {
7966                jarFile.close();
7967            } catch (IOException ignore) {}
7968        }
7969        return false;
7970    }
7971
7972    /**
7973     * Enforces code policy for the package. This ensures that if an APK has
7974     * declared hasCode="true" in its manifest that the APK actually contains
7975     * code.
7976     *
7977     * @throws PackageManagerException If bytecode could not be found when it should exist
7978     */
7979    private static void enforceCodePolicy(PackageParser.Package pkg)
7980            throws PackageManagerException {
7981        final boolean shouldHaveCode =
7982                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
7983        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
7984            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7985                    "Package " + pkg.baseCodePath + " code is missing");
7986        }
7987
7988        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
7989            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
7990                final boolean splitShouldHaveCode =
7991                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
7992                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
7993                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7994                            "Package " + pkg.splitCodePaths[i] + " code is missing");
7995                }
7996            }
7997        }
7998    }
7999
8000    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
8001            final int policyFlags, final int scanFlags, long currentTime, UserHandle user)
8002            throws PackageManagerException {
8003        final File scanFile = new File(pkg.codePath);
8004        if (pkg.applicationInfo.getCodePath() == null ||
8005                pkg.applicationInfo.getResourcePath() == null) {
8006            // Bail out. The resource and code paths haven't been set.
8007            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
8008                    "Code and resource paths haven't been set correctly");
8009        }
8010
8011        // Apply policy
8012        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
8013            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
8014            if (pkg.applicationInfo.isDirectBootAware()) {
8015                // we're direct boot aware; set for all components
8016                for (PackageParser.Service s : pkg.services) {
8017                    s.info.encryptionAware = s.info.directBootAware = true;
8018                }
8019                for (PackageParser.Provider p : pkg.providers) {
8020                    p.info.encryptionAware = p.info.directBootAware = true;
8021                }
8022                for (PackageParser.Activity a : pkg.activities) {
8023                    a.info.encryptionAware = a.info.directBootAware = true;
8024                }
8025                for (PackageParser.Activity r : pkg.receivers) {
8026                    r.info.encryptionAware = r.info.directBootAware = true;
8027                }
8028            }
8029        } else {
8030            // Only allow system apps to be flagged as core apps.
8031            pkg.coreApp = false;
8032            // clear flags not applicable to regular apps
8033            pkg.applicationInfo.privateFlags &=
8034                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
8035            pkg.applicationInfo.privateFlags &=
8036                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
8037        }
8038        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
8039
8040        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
8041            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8042        }
8043
8044        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
8045            enforceCodePolicy(pkg);
8046        }
8047
8048        if (mCustomResolverComponentName != null &&
8049                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
8050            setUpCustomResolverActivity(pkg);
8051        }
8052
8053        if (pkg.packageName.equals("android")) {
8054            synchronized (mPackages) {
8055                if (mAndroidApplication != null) {
8056                    Slog.w(TAG, "*************************************************");
8057                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
8058                    Slog.w(TAG, " file=" + scanFile);
8059                    Slog.w(TAG, "*************************************************");
8060                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8061                            "Core android package being redefined.  Skipping.");
8062                }
8063
8064                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8065                    // Set up information for our fall-back user intent resolution activity.
8066                    mPlatformPackage = pkg;
8067                    pkg.mVersionCode = mSdkVersion;
8068                    mAndroidApplication = pkg.applicationInfo;
8069
8070                    if (!mResolverReplaced) {
8071                        mResolveActivity.applicationInfo = mAndroidApplication;
8072                        mResolveActivity.name = ResolverActivity.class.getName();
8073                        mResolveActivity.packageName = mAndroidApplication.packageName;
8074                        mResolveActivity.processName = "system:ui";
8075                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8076                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
8077                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
8078                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8079                        mResolveActivity.exported = true;
8080                        mResolveActivity.enabled = true;
8081                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8082                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8083                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8084                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
8085                                | ActivityInfo.CONFIG_ORIENTATION
8086                                | ActivityInfo.CONFIG_KEYBOARD
8087                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8088                        mResolveInfo.activityInfo = mResolveActivity;
8089                        mResolveInfo.priority = 0;
8090                        mResolveInfo.preferredOrder = 0;
8091                        mResolveInfo.match = 0;
8092                        mResolveComponentName = new ComponentName(
8093                                mAndroidApplication.packageName, mResolveActivity.name);
8094                    }
8095                }
8096            }
8097        }
8098
8099        if (DEBUG_PACKAGE_SCANNING) {
8100            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8101                Log.d(TAG, "Scanning package " + pkg.packageName);
8102        }
8103
8104        synchronized (mPackages) {
8105            if (mPackages.containsKey(pkg.packageName)
8106                    || mSharedLibraries.containsKey(pkg.packageName)) {
8107                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
8108                        "Application package " + pkg.packageName
8109                                + " already installed.  Skipping duplicate.");
8110            }
8111
8112            // If we're only installing presumed-existing packages, require that the
8113            // scanned APK is both already known and at the path previously established
8114            // for it.  Previously unknown packages we pick up normally, but if we have an
8115            // a priori expectation about this package's install presence, enforce it.
8116            // With a singular exception for new system packages. When an OTA contains
8117            // a new system package, we allow the codepath to change from a system location
8118            // to the user-installed location. If we don't allow this change, any newer,
8119            // user-installed version of the application will be ignored.
8120            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
8121                if (mExpectingBetter.containsKey(pkg.packageName)) {
8122                    logCriticalInfo(Log.WARN,
8123                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
8124                } else {
8125                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
8126                    if (known != null) {
8127                        if (DEBUG_PACKAGE_SCANNING) {
8128                            Log.d(TAG, "Examining " + pkg.codePath
8129                                    + " and requiring known paths " + known.codePathString
8130                                    + " & " + known.resourcePathString);
8131                        }
8132                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
8133                                || !pkg.applicationInfo.getResourcePath().equals(
8134                                known.resourcePathString)) {
8135                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
8136                                    "Application package " + pkg.packageName
8137                                            + " found at " + pkg.applicationInfo.getCodePath()
8138                                            + " but expected at " + known.codePathString
8139                                            + "; ignoring.");
8140                        }
8141                    }
8142                }
8143            }
8144        }
8145
8146        // Initialize package source and resource directories
8147        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
8148        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
8149
8150        SharedUserSetting suid = null;
8151        PackageSetting pkgSetting = null;
8152
8153        if (!isSystemApp(pkg)) {
8154            // Only system apps can use these features.
8155            pkg.mOriginalPackages = null;
8156            pkg.mRealPackage = null;
8157            pkg.mAdoptPermissions = null;
8158        }
8159
8160        // Getting the package setting may have a side-effect, so if we
8161        // are only checking if scan would succeed, stash a copy of the
8162        // old setting to restore at the end.
8163        PackageSetting nonMutatedPs = null;
8164
8165        // writer
8166        synchronized (mPackages) {
8167            if (pkg.mSharedUserId != null) {
8168                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
8169                if (suid == null) {
8170                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8171                            "Creating application package " + pkg.packageName
8172                            + " for shared user failed");
8173                }
8174                if (DEBUG_PACKAGE_SCANNING) {
8175                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8176                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
8177                                + "): packages=" + suid.packages);
8178                }
8179            }
8180
8181            // Check if we are renaming from an original package name.
8182            PackageSetting origPackage = null;
8183            String realName = null;
8184            if (pkg.mOriginalPackages != null) {
8185                // This package may need to be renamed to a previously
8186                // installed name.  Let's check on that...
8187                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
8188                if (pkg.mOriginalPackages.contains(renamed)) {
8189                    // This package had originally been installed as the
8190                    // original name, and we have already taken care of
8191                    // transitioning to the new one.  Just update the new
8192                    // one to continue using the old name.
8193                    realName = pkg.mRealPackage;
8194                    if (!pkg.packageName.equals(renamed)) {
8195                        // Callers into this function may have already taken
8196                        // care of renaming the package; only do it here if
8197                        // it is not already done.
8198                        pkg.setPackageName(renamed);
8199                    }
8200
8201                } else {
8202                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
8203                        if ((origPackage = mSettings.peekPackageLPr(
8204                                pkg.mOriginalPackages.get(i))) != null) {
8205                            // We do have the package already installed under its
8206                            // original name...  should we use it?
8207                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
8208                                // New package is not compatible with original.
8209                                origPackage = null;
8210                                continue;
8211                            } else if (origPackage.sharedUser != null) {
8212                                // Make sure uid is compatible between packages.
8213                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
8214                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
8215                                            + " to " + pkg.packageName + ": old uid "
8216                                            + origPackage.sharedUser.name
8217                                            + " differs from " + pkg.mSharedUserId);
8218                                    origPackage = null;
8219                                    continue;
8220                                }
8221                                // TODO: Add case when shared user id is added [b/28144775]
8222                            } else {
8223                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
8224                                        + pkg.packageName + " to old name " + origPackage.name);
8225                            }
8226                            break;
8227                        }
8228                    }
8229                }
8230            }
8231
8232            if (mTransferedPackages.contains(pkg.packageName)) {
8233                Slog.w(TAG, "Package " + pkg.packageName
8234                        + " was transferred to another, but its .apk remains");
8235            }
8236
8237            // See comments in nonMutatedPs declaration
8238            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8239                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
8240                if (foundPs != null) {
8241                    nonMutatedPs = new PackageSetting(foundPs);
8242                }
8243            }
8244
8245            // Just create the setting, don't add it yet. For already existing packages
8246            // the PkgSetting exists already and doesn't have to be created.
8247            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
8248                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
8249                    pkg.applicationInfo.primaryCpuAbi,
8250                    pkg.applicationInfo.secondaryCpuAbi,
8251                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
8252                    user, false);
8253            if (pkgSetting == null) {
8254                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
8255                        "Creating application package " + pkg.packageName + " failed");
8256            }
8257
8258            if (pkgSetting.origPackage != null) {
8259                // If we are first transitioning from an original package,
8260                // fix up the new package's name now.  We need to do this after
8261                // looking up the package under its new name, so getPackageLP
8262                // can take care of fiddling things correctly.
8263                pkg.setPackageName(origPackage.name);
8264
8265                // File a report about this.
8266                String msg = "New package " + pkgSetting.realName
8267                        + " renamed to replace old package " + pkgSetting.name;
8268                reportSettingsProblem(Log.WARN, msg);
8269
8270                // Make a note of it.
8271                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8272                    mTransferedPackages.add(origPackage.name);
8273                }
8274
8275                // No longer need to retain this.
8276                pkgSetting.origPackage = null;
8277            }
8278
8279            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
8280                // Make a note of it.
8281                mTransferedPackages.add(pkg.packageName);
8282            }
8283
8284            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
8285                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8286            }
8287
8288            if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8289                // Check all shared libraries and map to their actual file path.
8290                // We only do this here for apps not on a system dir, because those
8291                // are the only ones that can fail an install due to this.  We
8292                // will take care of the system apps by updating all of their
8293                // library paths after the scan is done.
8294                updateSharedLibrariesLPw(pkg, null);
8295            }
8296
8297            if (mFoundPolicyFile) {
8298                SELinuxMMAC.assignSeinfoValue(pkg);
8299            }
8300
8301            pkg.applicationInfo.uid = pkgSetting.appId;
8302            pkg.mExtras = pkgSetting;
8303            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
8304                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
8305                    // We just determined the app is signed correctly, so bring
8306                    // over the latest parsed certs.
8307                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8308                } else {
8309                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8310                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8311                                "Package " + pkg.packageName + " upgrade keys do not match the "
8312                                + "previously installed version");
8313                    } else {
8314                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
8315                        String msg = "System package " + pkg.packageName
8316                            + " signature changed; retaining data.";
8317                        reportSettingsProblem(Log.WARN, msg);
8318                    }
8319                }
8320            } else {
8321                try {
8322                    verifySignaturesLP(pkgSetting, pkg);
8323                    // We just determined the app is signed correctly, so bring
8324                    // over the latest parsed certs.
8325                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8326                } catch (PackageManagerException e) {
8327                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
8328                        throw e;
8329                    }
8330                    // The signature has changed, but this package is in the system
8331                    // image...  let's recover!
8332                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
8333                    // However...  if this package is part of a shared user, but it
8334                    // doesn't match the signature of the shared user, let's fail.
8335                    // What this means is that you can't change the signatures
8336                    // associated with an overall shared user, which doesn't seem all
8337                    // that unreasonable.
8338                    if (pkgSetting.sharedUser != null) {
8339                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
8340                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
8341                            throw new PackageManagerException(
8342                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
8343                                            "Signature mismatch for shared user: "
8344                                            + pkgSetting.sharedUser);
8345                        }
8346                    }
8347                    // File a report about this.
8348                    String msg = "System package " + pkg.packageName
8349                        + " signature changed; retaining data.";
8350                    reportSettingsProblem(Log.WARN, msg);
8351                }
8352            }
8353            // Verify that this new package doesn't have any content providers
8354            // that conflict with existing packages.  Only do this if the
8355            // package isn't already installed, since we don't want to break
8356            // things that are installed.
8357            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
8358                final int N = pkg.providers.size();
8359                int i;
8360                for (i=0; i<N; i++) {
8361                    PackageParser.Provider p = pkg.providers.get(i);
8362                    if (p.info.authority != null) {
8363                        String names[] = p.info.authority.split(";");
8364                        for (int j = 0; j < names.length; j++) {
8365                            if (mProvidersByAuthority.containsKey(names[j])) {
8366                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8367                                final String otherPackageName =
8368                                        ((other != null && other.getComponentName() != null) ?
8369                                                other.getComponentName().getPackageName() : "?");
8370                                throw new PackageManagerException(
8371                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
8372                                                "Can't install because provider name " + names[j]
8373                                                + " (in package " + pkg.applicationInfo.packageName
8374                                                + ") is already used by " + otherPackageName);
8375                            }
8376                        }
8377                    }
8378                }
8379            }
8380
8381            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
8382                // This package wants to adopt ownership of permissions from
8383                // another package.
8384                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
8385                    final String origName = pkg.mAdoptPermissions.get(i);
8386                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
8387                    if (orig != null) {
8388                        if (verifyPackageUpdateLPr(orig, pkg)) {
8389                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
8390                                    + pkg.packageName);
8391                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
8392                        }
8393                    }
8394                }
8395            }
8396        }
8397
8398        final String pkgName = pkg.packageName;
8399
8400        final long scanFileTime = scanFile.lastModified();
8401        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
8402        pkg.applicationInfo.processName = fixProcessName(
8403                pkg.applicationInfo.packageName,
8404                pkg.applicationInfo.processName,
8405                pkg.applicationInfo.uid);
8406
8407        if (pkg != mPlatformPackage) {
8408            // Get all of our default paths setup
8409            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
8410        }
8411
8412        final String path = scanFile.getPath();
8413        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
8414
8415        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
8416            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
8417
8418            // Some system apps still use directory structure for native libraries
8419            // in which case we might end up not detecting abi solely based on apk
8420            // structure. Try to detect abi based on directory structure.
8421            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
8422                    pkg.applicationInfo.primaryCpuAbi == null) {
8423                setBundledAppAbisAndRoots(pkg, pkgSetting);
8424                setNativeLibraryPaths(pkg);
8425            }
8426
8427        } else {
8428            if ((scanFlags & SCAN_MOVE) != 0) {
8429                // We haven't run dex-opt for this move (since we've moved the compiled output too)
8430                // but we already have this packages package info in the PackageSetting. We just
8431                // use that and derive the native library path based on the new codepath.
8432                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
8433                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
8434            }
8435
8436            // Set native library paths again. For moves, the path will be updated based on the
8437            // ABIs we've determined above. For non-moves, the path will be updated based on the
8438            // ABIs we determined during compilation, but the path will depend on the final
8439            // package path (after the rename away from the stage path).
8440            setNativeLibraryPaths(pkg);
8441        }
8442
8443        // This is a special case for the "system" package, where the ABI is
8444        // dictated by the zygote configuration (and init.rc). We should keep track
8445        // of this ABI so that we can deal with "normal" applications that run under
8446        // the same UID correctly.
8447        if (mPlatformPackage == pkg) {
8448            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
8449                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
8450        }
8451
8452        // If there's a mismatch between the abi-override in the package setting
8453        // and the abiOverride specified for the install. Warn about this because we
8454        // would've already compiled the app without taking the package setting into
8455        // account.
8456        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
8457            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
8458                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
8459                        " for package " + pkg.packageName);
8460            }
8461        }
8462
8463        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8464        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8465        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
8466
8467        // Copy the derived override back to the parsed package, so that we can
8468        // update the package settings accordingly.
8469        pkg.cpuAbiOverride = cpuAbiOverride;
8470
8471        if (DEBUG_ABI_SELECTION) {
8472            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
8473                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
8474                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
8475        }
8476
8477        // Push the derived path down into PackageSettings so we know what to
8478        // clean up at uninstall time.
8479        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
8480
8481        if (DEBUG_ABI_SELECTION) {
8482            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
8483                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
8484                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
8485        }
8486
8487        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
8488            // We don't do this here during boot because we can do it all
8489            // at once after scanning all existing packages.
8490            //
8491            // We also do this *before* we perform dexopt on this package, so that
8492            // we can avoid redundant dexopts, and also to make sure we've got the
8493            // code and package path correct.
8494            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
8495                    pkg, true /* boot complete */);
8496        }
8497
8498        if (mFactoryTest && pkg.requestedPermissions.contains(
8499                android.Manifest.permission.FACTORY_TEST)) {
8500            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8501        }
8502
8503        ArrayList<PackageParser.Package> clientLibPkgs = null;
8504
8505        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8506            if (nonMutatedPs != null) {
8507                synchronized (mPackages) {
8508                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8509                }
8510            }
8511            return pkg;
8512        }
8513
8514        // Only privileged apps and updated privileged apps can add child packages.
8515        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8516            if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
8517                throw new PackageManagerException("Only privileged apps and updated "
8518                        + "privileged apps can add child packages. Ignoring package "
8519                        + pkg.packageName);
8520            }
8521            final int childCount = pkg.childPackages.size();
8522            for (int i = 0; i < childCount; i++) {
8523                PackageParser.Package childPkg = pkg.childPackages.get(i);
8524                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8525                        childPkg.packageName)) {
8526                    throw new PackageManagerException("Cannot override a child package of "
8527                            + "another disabled system app. Ignoring package " + pkg.packageName);
8528                }
8529            }
8530        }
8531
8532        // writer
8533        synchronized (mPackages) {
8534            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8535                // Only system apps can add new shared libraries.
8536                if (pkg.libraryNames != null) {
8537                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8538                        String name = pkg.libraryNames.get(i);
8539                        boolean allowed = false;
8540                        if (pkg.isUpdatedSystemApp()) {
8541                            // New library entries can only be added through the
8542                            // system image.  This is important to get rid of a lot
8543                            // of nasty edge cases: for example if we allowed a non-
8544                            // system update of the app to add a library, then uninstalling
8545                            // the update would make the library go away, and assumptions
8546                            // we made such as through app install filtering would now
8547                            // have allowed apps on the device which aren't compatible
8548                            // with it.  Better to just have the restriction here, be
8549                            // conservative, and create many fewer cases that can negatively
8550                            // impact the user experience.
8551                            final PackageSetting sysPs = mSettings
8552                                    .getDisabledSystemPkgLPr(pkg.packageName);
8553                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8554                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8555                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8556                                        allowed = true;
8557                                        break;
8558                                    }
8559                                }
8560                            }
8561                        } else {
8562                            allowed = true;
8563                        }
8564                        if (allowed) {
8565                            if (!mSharedLibraries.containsKey(name)) {
8566                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8567                            } else if (!name.equals(pkg.packageName)) {
8568                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8569                                        + name + " already exists; skipping");
8570                            }
8571                        } else {
8572                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8573                                    + name + " that is not declared on system image; skipping");
8574                        }
8575                    }
8576                    if ((scanFlags & SCAN_BOOTING) == 0) {
8577                        // If we are not booting, we need to update any applications
8578                        // that are clients of our shared library.  If we are booting,
8579                        // this will all be done once the scan is complete.
8580                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8581                    }
8582                }
8583            }
8584        }
8585
8586        if ((scanFlags & SCAN_BOOTING) != 0) {
8587            // No apps can run during boot scan, so they don't need to be frozen
8588        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
8589            // Caller asked to not kill app, so it's probably not frozen
8590        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
8591            // Caller asked us to ignore frozen check for some reason; they
8592            // probably didn't know the package name
8593        } else {
8594            // We're doing major surgery on this package, so it better be frozen
8595            // right now to keep it from launching
8596            checkPackageFrozen(pkgName);
8597        }
8598
8599        // Also need to kill any apps that are dependent on the library.
8600        if (clientLibPkgs != null) {
8601            for (int i=0; i<clientLibPkgs.size(); i++) {
8602                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8603                killApplication(clientPkg.applicationInfo.packageName,
8604                        clientPkg.applicationInfo.uid, "update lib");
8605            }
8606        }
8607
8608        // Make sure we're not adding any bogus keyset info
8609        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8610        ksms.assertScannedPackageValid(pkg);
8611
8612        // writer
8613        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8614
8615        boolean createIdmapFailed = false;
8616        synchronized (mPackages) {
8617            // We don't expect installation to fail beyond this point
8618
8619            if (pkgSetting.pkg != null) {
8620                // Note that |user| might be null during the initial boot scan. If a codePath
8621                // for an app has changed during a boot scan, it's due to an app update that's
8622                // part of the system partition and marker changes must be applied to all users.
8623                maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg,
8624                    (user != null) ? user : UserHandle.ALL);
8625            }
8626
8627            // Add the new setting to mSettings
8628            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8629            // Add the new setting to mPackages
8630            mPackages.put(pkg.applicationInfo.packageName, pkg);
8631            // Make sure we don't accidentally delete its data.
8632            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8633            while (iter.hasNext()) {
8634                PackageCleanItem item = iter.next();
8635                if (pkgName.equals(item.packageName)) {
8636                    iter.remove();
8637                }
8638            }
8639
8640            // Take care of first install / last update times.
8641            if (currentTime != 0) {
8642                if (pkgSetting.firstInstallTime == 0) {
8643                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8644                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8645                    pkgSetting.lastUpdateTime = currentTime;
8646                }
8647            } else if (pkgSetting.firstInstallTime == 0) {
8648                // We need *something*.  Take time time stamp of the file.
8649                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8650            } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8651                if (scanFileTime != pkgSetting.timeStamp) {
8652                    // A package on the system image has changed; consider this
8653                    // to be an update.
8654                    pkgSetting.lastUpdateTime = scanFileTime;
8655                }
8656            }
8657
8658            // Add the package's KeySets to the global KeySetManagerService
8659            ksms.addScannedPackageLPw(pkg);
8660
8661            int N = pkg.providers.size();
8662            StringBuilder r = null;
8663            int i;
8664            for (i=0; i<N; i++) {
8665                PackageParser.Provider p = pkg.providers.get(i);
8666                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8667                        p.info.processName, pkg.applicationInfo.uid);
8668                mProviders.addProvider(p);
8669                p.syncable = p.info.isSyncable;
8670                if (p.info.authority != null) {
8671                    String names[] = p.info.authority.split(";");
8672                    p.info.authority = null;
8673                    for (int j = 0; j < names.length; j++) {
8674                        if (j == 1 && p.syncable) {
8675                            // We only want the first authority for a provider to possibly be
8676                            // syncable, so if we already added this provider using a different
8677                            // authority clear the syncable flag. We copy the provider before
8678                            // changing it because the mProviders object contains a reference
8679                            // to a provider that we don't want to change.
8680                            // Only do this for the second authority since the resulting provider
8681                            // object can be the same for all future authorities for this provider.
8682                            p = new PackageParser.Provider(p);
8683                            p.syncable = false;
8684                        }
8685                        if (!mProvidersByAuthority.containsKey(names[j])) {
8686                            mProvidersByAuthority.put(names[j], p);
8687                            if (p.info.authority == null) {
8688                                p.info.authority = names[j];
8689                            } else {
8690                                p.info.authority = p.info.authority + ";" + names[j];
8691                            }
8692                            if (DEBUG_PACKAGE_SCANNING) {
8693                                if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
8694                                    Log.d(TAG, "Registered content provider: " + names[j]
8695                                            + ", className = " + p.info.name + ", isSyncable = "
8696                                            + p.info.isSyncable);
8697                            }
8698                        } else {
8699                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8700                            Slog.w(TAG, "Skipping provider name " + names[j] +
8701                                    " (in package " + pkg.applicationInfo.packageName +
8702                                    "): name already used by "
8703                                    + ((other != null && other.getComponentName() != null)
8704                                            ? other.getComponentName().getPackageName() : "?"));
8705                        }
8706                    }
8707                }
8708                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8709                    if (r == null) {
8710                        r = new StringBuilder(256);
8711                    } else {
8712                        r.append(' ');
8713                    }
8714                    r.append(p.info.name);
8715                }
8716            }
8717            if (r != null) {
8718                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8719            }
8720
8721            N = pkg.services.size();
8722            r = null;
8723            for (i=0; i<N; i++) {
8724                PackageParser.Service s = pkg.services.get(i);
8725                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8726                        s.info.processName, pkg.applicationInfo.uid);
8727                mServices.addService(s);
8728                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8729                    if (r == null) {
8730                        r = new StringBuilder(256);
8731                    } else {
8732                        r.append(' ');
8733                    }
8734                    r.append(s.info.name);
8735                }
8736            }
8737            if (r != null) {
8738                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8739            }
8740
8741            N = pkg.receivers.size();
8742            r = null;
8743            for (i=0; i<N; i++) {
8744                PackageParser.Activity a = pkg.receivers.get(i);
8745                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8746                        a.info.processName, pkg.applicationInfo.uid);
8747                mReceivers.addActivity(a, "receiver");
8748                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8749                    if (r == null) {
8750                        r = new StringBuilder(256);
8751                    } else {
8752                        r.append(' ');
8753                    }
8754                    r.append(a.info.name);
8755                }
8756            }
8757            if (r != null) {
8758                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8759            }
8760
8761            N = pkg.activities.size();
8762            r = null;
8763            for (i=0; i<N; i++) {
8764                PackageParser.Activity a = pkg.activities.get(i);
8765                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8766                        a.info.processName, pkg.applicationInfo.uid);
8767                mActivities.addActivity(a, "activity");
8768                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8769                    if (r == null) {
8770                        r = new StringBuilder(256);
8771                    } else {
8772                        r.append(' ');
8773                    }
8774                    r.append(a.info.name);
8775                }
8776            }
8777            if (r != null) {
8778                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8779            }
8780
8781            N = pkg.permissionGroups.size();
8782            r = null;
8783            for (i=0; i<N; i++) {
8784                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8785                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8786                if (cur == null) {
8787                    mPermissionGroups.put(pg.info.name, pg);
8788                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8789                        if (r == null) {
8790                            r = new StringBuilder(256);
8791                        } else {
8792                            r.append(' ');
8793                        }
8794                        r.append(pg.info.name);
8795                    }
8796                } else {
8797                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8798                            + pg.info.packageName + " ignored: original from "
8799                            + cur.info.packageName);
8800                    if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8801                        if (r == null) {
8802                            r = new StringBuilder(256);
8803                        } else {
8804                            r.append(' ');
8805                        }
8806                        r.append("DUP:");
8807                        r.append(pg.info.name);
8808                    }
8809                }
8810            }
8811            if (r != null) {
8812                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8813            }
8814
8815            N = pkg.permissions.size();
8816            r = null;
8817            for (i=0; i<N; i++) {
8818                PackageParser.Permission p = pkg.permissions.get(i);
8819
8820                // Assume by default that we did not install this permission into the system.
8821                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8822
8823                // Now that permission groups have a special meaning, we ignore permission
8824                // groups for legacy apps to prevent unexpected behavior. In particular,
8825                // permissions for one app being granted to someone just becase they happen
8826                // to be in a group defined by another app (before this had no implications).
8827                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8828                    p.group = mPermissionGroups.get(p.info.group);
8829                    // Warn for a permission in an unknown group.
8830                    if (p.info.group != null && p.group == null) {
8831                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8832                                + p.info.packageName + " in an unknown group " + p.info.group);
8833                    }
8834                }
8835
8836                ArrayMap<String, BasePermission> permissionMap =
8837                        p.tree ? mSettings.mPermissionTrees
8838                                : mSettings.mPermissions;
8839                BasePermission bp = permissionMap.get(p.info.name);
8840
8841                // Allow system apps to redefine non-system permissions
8842                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8843                    final boolean currentOwnerIsSystem = (bp.perm != null
8844                            && isSystemApp(bp.perm.owner));
8845                    if (isSystemApp(p.owner)) {
8846                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8847                            // It's a built-in permission and no owner, take ownership now
8848                            bp.packageSetting = pkgSetting;
8849                            bp.perm = p;
8850                            bp.uid = pkg.applicationInfo.uid;
8851                            bp.sourcePackage = p.info.packageName;
8852                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8853                        } else if (!currentOwnerIsSystem) {
8854                            String msg = "New decl " + p.owner + " of permission  "
8855                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8856                            reportSettingsProblem(Log.WARN, msg);
8857                            bp = null;
8858                        }
8859                    }
8860                }
8861
8862                if (bp == null) {
8863                    bp = new BasePermission(p.info.name, p.info.packageName,
8864                            BasePermission.TYPE_NORMAL);
8865                    permissionMap.put(p.info.name, bp);
8866                }
8867
8868                if (bp.perm == null) {
8869                    if (bp.sourcePackage == null
8870                            || bp.sourcePackage.equals(p.info.packageName)) {
8871                        BasePermission tree = findPermissionTreeLP(p.info.name);
8872                        if (tree == null
8873                                || tree.sourcePackage.equals(p.info.packageName)) {
8874                            bp.packageSetting = pkgSetting;
8875                            bp.perm = p;
8876                            bp.uid = pkg.applicationInfo.uid;
8877                            bp.sourcePackage = p.info.packageName;
8878                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8879                            if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8880                                if (r == null) {
8881                                    r = new StringBuilder(256);
8882                                } else {
8883                                    r.append(' ');
8884                                }
8885                                r.append(p.info.name);
8886                            }
8887                        } else {
8888                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8889                                    + p.info.packageName + " ignored: base tree "
8890                                    + tree.name + " is from package "
8891                                    + tree.sourcePackage);
8892                        }
8893                    } else {
8894                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8895                                + p.info.packageName + " ignored: original from "
8896                                + bp.sourcePackage);
8897                    }
8898                } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8899                    if (r == null) {
8900                        r = new StringBuilder(256);
8901                    } else {
8902                        r.append(' ');
8903                    }
8904                    r.append("DUP:");
8905                    r.append(p.info.name);
8906                }
8907                if (bp.perm == p) {
8908                    bp.protectionLevel = p.info.protectionLevel;
8909                }
8910            }
8911
8912            if (r != null) {
8913                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8914            }
8915
8916            N = pkg.instrumentation.size();
8917            r = null;
8918            for (i=0; i<N; i++) {
8919                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8920                a.info.packageName = pkg.applicationInfo.packageName;
8921                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8922                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8923                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8924                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8925                a.info.dataDir = pkg.applicationInfo.dataDir;
8926                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8927                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8928
8929                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8930                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
8931                mInstrumentation.put(a.getComponentName(), a);
8932                if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) {
8933                    if (r == null) {
8934                        r = new StringBuilder(256);
8935                    } else {
8936                        r.append(' ');
8937                    }
8938                    r.append(a.info.name);
8939                }
8940            }
8941            if (r != null) {
8942                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8943            }
8944
8945            if (pkg.protectedBroadcasts != null) {
8946                N = pkg.protectedBroadcasts.size();
8947                for (i=0; i<N; i++) {
8948                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8949                }
8950            }
8951
8952            pkgSetting.setTimeStamp(scanFileTime);
8953
8954            // Create idmap files for pairs of (packages, overlay packages).
8955            // Note: "android", ie framework-res.apk, is handled by native layers.
8956            if (pkg.mOverlayTarget != null) {
8957                // This is an overlay package.
8958                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8959                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8960                        mOverlays.put(pkg.mOverlayTarget,
8961                                new ArrayMap<String, PackageParser.Package>());
8962                    }
8963                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8964                    map.put(pkg.packageName, pkg);
8965                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8966                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8967                        createIdmapFailed = true;
8968                    }
8969                }
8970            } else if (mOverlays.containsKey(pkg.packageName) &&
8971                    !pkg.packageName.equals("android")) {
8972                // This is a regular package, with one or more known overlay packages.
8973                createIdmapsForPackageLI(pkg);
8974            }
8975        }
8976
8977        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8978
8979        if (createIdmapFailed) {
8980            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8981                    "scanPackageLI failed to createIdmap");
8982        }
8983        return pkg;
8984    }
8985
8986    private void maybeRenameForeignDexMarkers(PackageParser.Package existing,
8987            PackageParser.Package update, UserHandle user) {
8988        if (existing.applicationInfo == null || update.applicationInfo == null) {
8989            // This isn't due to an app installation.
8990            return;
8991        }
8992
8993        final File oldCodePath = new File(existing.applicationInfo.getCodePath());
8994        final File newCodePath = new File(update.applicationInfo.getCodePath());
8995
8996        // The codePath hasn't changed, so there's nothing for us to do.
8997        if (Objects.equals(oldCodePath, newCodePath)) {
8998            return;
8999        }
9000
9001        File canonicalNewCodePath;
9002        try {
9003            canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath));
9004        } catch (IOException e) {
9005            Slog.w(TAG, "Failed to get canonical path.", e);
9006            return;
9007        }
9008
9009        // This is a bit of a hack. The oldCodePath doesn't exist at this point (because
9010        // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume
9011        // that the last component of the path (i.e, the name) doesn't need canonicalization
9012        // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now
9013        // but may change in the future. Hopefully this function won't exist at that point.
9014        final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(),
9015                oldCodePath.getName());
9016
9017        // Calculate the prefixes of the markers. These are just the paths with "/" replaced
9018        // with "@".
9019        String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@');
9020        if (!oldMarkerPrefix.endsWith("@")) {
9021            oldMarkerPrefix += "@";
9022        }
9023        String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@');
9024        if (!newMarkerPrefix.endsWith("@")) {
9025            newMarkerPrefix += "@";
9026        }
9027
9028        List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly();
9029        List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size());
9030        for (String updatedPath : updatedPaths) {
9031            String updatedPathName = new File(updatedPath).getName();
9032            markerSuffixes.add(updatedPathName.replace('/', '@'));
9033        }
9034
9035        for (int userId : resolveUserIds(user.getIdentifier())) {
9036            File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId);
9037
9038            for (String markerSuffix : markerSuffixes) {
9039                File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix);
9040                File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix);
9041                if (oldForeignUseMark.exists()) {
9042                    try {
9043                        Os.rename(oldForeignUseMark.getAbsolutePath(),
9044                                newForeignUseMark.getAbsolutePath());
9045                    } catch (ErrnoException e) {
9046                        Slog.w(TAG, "Failed to rename foreign use marker", e);
9047                        oldForeignUseMark.delete();
9048                    }
9049                }
9050            }
9051        }
9052    }
9053
9054    /**
9055     * Derive the ABI of a non-system package located at {@code scanFile}. This information
9056     * is derived purely on the basis of the contents of {@code scanFile} and
9057     * {@code cpuAbiOverride}.
9058     *
9059     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
9060     */
9061    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
9062                                 String cpuAbiOverride, boolean extractLibs)
9063            throws PackageManagerException {
9064        // TODO: We can probably be smarter about this stuff. For installed apps,
9065        // we can calculate this information at install time once and for all. For
9066        // system apps, we can probably assume that this information doesn't change
9067        // after the first boot scan. As things stand, we do lots of unnecessary work.
9068
9069        // Give ourselves some initial paths; we'll come back for another
9070        // pass once we've determined ABI below.
9071        setNativeLibraryPaths(pkg);
9072
9073        // We would never need to extract libs for forward-locked and external packages,
9074        // since the container service will do it for us. We shouldn't attempt to
9075        // extract libs from system app when it was not updated.
9076        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
9077                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
9078            extractLibs = false;
9079        }
9080
9081        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
9082        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
9083
9084        NativeLibraryHelper.Handle handle = null;
9085        try {
9086            handle = NativeLibraryHelper.Handle.create(pkg);
9087            // TODO(multiArch): This can be null for apps that didn't go through the
9088            // usual installation process. We can calculate it again, like we
9089            // do during install time.
9090            //
9091            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
9092            // unnecessary.
9093            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
9094
9095            // Null out the abis so that they can be recalculated.
9096            pkg.applicationInfo.primaryCpuAbi = null;
9097            pkg.applicationInfo.secondaryCpuAbi = null;
9098            if (isMultiArch(pkg.applicationInfo)) {
9099                // Warn if we've set an abiOverride for multi-lib packages..
9100                // By definition, we need to copy both 32 and 64 bit libraries for
9101                // such packages.
9102                if (pkg.cpuAbiOverride != null
9103                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
9104                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
9105                }
9106
9107                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
9108                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
9109                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
9110                    if (extractLibs) {
9111                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9112                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
9113                                useIsaSpecificSubdirs);
9114                    } else {
9115                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
9116                    }
9117                }
9118
9119                maybeThrowExceptionForMultiArchCopy(
9120                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
9121
9122                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
9123                    if (extractLibs) {
9124                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9125                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
9126                                useIsaSpecificSubdirs);
9127                    } else {
9128                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
9129                    }
9130                }
9131
9132                maybeThrowExceptionForMultiArchCopy(
9133                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
9134
9135                if (abi64 >= 0) {
9136                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
9137                }
9138
9139                if (abi32 >= 0) {
9140                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
9141                    if (abi64 >= 0) {
9142                        if (pkg.use32bitAbi) {
9143                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
9144                            pkg.applicationInfo.primaryCpuAbi = abi;
9145                        } else {
9146                            pkg.applicationInfo.secondaryCpuAbi = abi;
9147                        }
9148                    } else {
9149                        pkg.applicationInfo.primaryCpuAbi = abi;
9150                    }
9151                }
9152
9153            } else {
9154                String[] abiList = (cpuAbiOverride != null) ?
9155                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
9156
9157                // Enable gross and lame hacks for apps that are built with old
9158                // SDK tools. We must scan their APKs for renderscript bitcode and
9159                // not launch them if it's present. Don't bother checking on devices
9160                // that don't have 64 bit support.
9161                boolean needsRenderScriptOverride = false;
9162                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
9163                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9164                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9165                    needsRenderScriptOverride = true;
9166                }
9167
9168                final int copyRet;
9169                if (extractLibs) {
9170                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
9171                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
9172                } else {
9173                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9174                }
9175
9176                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9177                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
9178                            "Error unpackaging native libs for app, errorCode=" + copyRet);
9179                }
9180
9181                if (copyRet >= 0) {
9182                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
9183                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
9184                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
9185                } else if (needsRenderScriptOverride) {
9186                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
9187                }
9188            }
9189        } catch (IOException ioe) {
9190            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
9191        } finally {
9192            IoUtils.closeQuietly(handle);
9193        }
9194
9195        // Now that we've calculated the ABIs and determined if it's an internal app,
9196        // we will go ahead and populate the nativeLibraryPath.
9197        setNativeLibraryPaths(pkg);
9198    }
9199
9200    /**
9201     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
9202     * i.e, so that all packages can be run inside a single process if required.
9203     *
9204     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
9205     * this function will either try and make the ABI for all packages in {@code packagesForUser}
9206     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
9207     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
9208     * updating a package that belongs to a shared user.
9209     *
9210     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
9211     * adds unnecessary complexity.
9212     */
9213    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
9214            PackageParser.Package scannedPackage, boolean bootComplete) {
9215        String requiredInstructionSet = null;
9216        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
9217            requiredInstructionSet = VMRuntime.getInstructionSet(
9218                     scannedPackage.applicationInfo.primaryCpuAbi);
9219        }
9220
9221        PackageSetting requirer = null;
9222        for (PackageSetting ps : packagesForUser) {
9223            // If packagesForUser contains scannedPackage, we skip it. This will happen
9224            // when scannedPackage is an update of an existing package. Without this check,
9225            // we will never be able to change the ABI of any package belonging to a shared
9226            // user, even if it's compatible with other packages.
9227            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9228                if (ps.primaryCpuAbiString == null) {
9229                    continue;
9230                }
9231
9232                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
9233                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
9234                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
9235                    // this but there's not much we can do.
9236                    String errorMessage = "Instruction set mismatch, "
9237                            + ((requirer == null) ? "[caller]" : requirer)
9238                            + " requires " + requiredInstructionSet + " whereas " + ps
9239                            + " requires " + instructionSet;
9240                    Slog.w(TAG, errorMessage);
9241                }
9242
9243                if (requiredInstructionSet == null) {
9244                    requiredInstructionSet = instructionSet;
9245                    requirer = ps;
9246                }
9247            }
9248        }
9249
9250        if (requiredInstructionSet != null) {
9251            String adjustedAbi;
9252            if (requirer != null) {
9253                // requirer != null implies that either scannedPackage was null or that scannedPackage
9254                // did not require an ABI, in which case we have to adjust scannedPackage to match
9255                // the ABI of the set (which is the same as requirer's ABI)
9256                adjustedAbi = requirer.primaryCpuAbiString;
9257                if (scannedPackage != null) {
9258                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
9259                }
9260            } else {
9261                // requirer == null implies that we're updating all ABIs in the set to
9262                // match scannedPackage.
9263                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
9264            }
9265
9266            for (PackageSetting ps : packagesForUser) {
9267                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
9268                    if (ps.primaryCpuAbiString != null) {
9269                        continue;
9270                    }
9271
9272                    ps.primaryCpuAbiString = adjustedAbi;
9273                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
9274                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
9275                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
9276                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
9277                                + " (requirer="
9278                                + (requirer == null ? "null" : requirer.pkg.packageName)
9279                                + ", scannedPackage="
9280                                + (scannedPackage != null ? scannedPackage.packageName : "null")
9281                                + ")");
9282                        try {
9283                            mInstaller.rmdex(ps.codePathString,
9284                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
9285                        } catch (InstallerException ignored) {
9286                        }
9287                    }
9288                }
9289            }
9290        }
9291    }
9292
9293    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
9294        synchronized (mPackages) {
9295            mResolverReplaced = true;
9296            // Set up information for custom user intent resolution activity.
9297            mResolveActivity.applicationInfo = pkg.applicationInfo;
9298            mResolveActivity.name = mCustomResolverComponentName.getClassName();
9299            mResolveActivity.packageName = pkg.applicationInfo.packageName;
9300            mResolveActivity.processName = pkg.applicationInfo.packageName;
9301            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9302            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9303                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9304            mResolveActivity.theme = 0;
9305            mResolveActivity.exported = true;
9306            mResolveActivity.enabled = true;
9307            mResolveInfo.activityInfo = mResolveActivity;
9308            mResolveInfo.priority = 0;
9309            mResolveInfo.preferredOrder = 0;
9310            mResolveInfo.match = 0;
9311            mResolveComponentName = mCustomResolverComponentName;
9312            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
9313                    mResolveComponentName);
9314        }
9315    }
9316
9317    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
9318        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
9319
9320        // Set up information for ephemeral installer activity
9321        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
9322        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
9323        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
9324        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
9325        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
9326        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
9327                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
9328        mEphemeralInstallerActivity.theme = 0;
9329        mEphemeralInstallerActivity.exported = true;
9330        mEphemeralInstallerActivity.enabled = true;
9331        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
9332        mEphemeralInstallerInfo.priority = 0;
9333        mEphemeralInstallerInfo.preferredOrder = 0;
9334        mEphemeralInstallerInfo.match = 0;
9335
9336        if (DEBUG_EPHEMERAL) {
9337            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
9338        }
9339    }
9340
9341    private static String calculateBundledApkRoot(final String codePathString) {
9342        final File codePath = new File(codePathString);
9343        final File codeRoot;
9344        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
9345            codeRoot = Environment.getRootDirectory();
9346        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
9347            codeRoot = Environment.getOemDirectory();
9348        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
9349            codeRoot = Environment.getVendorDirectory();
9350        } else {
9351            // Unrecognized code path; take its top real segment as the apk root:
9352            // e.g. /something/app/blah.apk => /something
9353            try {
9354                File f = codePath.getCanonicalFile();
9355                File parent = f.getParentFile();    // non-null because codePath is a file
9356                File tmp;
9357                while ((tmp = parent.getParentFile()) != null) {
9358                    f = parent;
9359                    parent = tmp;
9360                }
9361                codeRoot = f;
9362                Slog.w(TAG, "Unrecognized code path "
9363                        + codePath + " - using " + codeRoot);
9364            } catch (IOException e) {
9365                // Can't canonicalize the code path -- shenanigans?
9366                Slog.w(TAG, "Can't canonicalize code path " + codePath);
9367                return Environment.getRootDirectory().getPath();
9368            }
9369        }
9370        return codeRoot.getPath();
9371    }
9372
9373    /**
9374     * Derive and set the location of native libraries for the given package,
9375     * which varies depending on where and how the package was installed.
9376     */
9377    private void setNativeLibraryPaths(PackageParser.Package pkg) {
9378        final ApplicationInfo info = pkg.applicationInfo;
9379        final String codePath = pkg.codePath;
9380        final File codeFile = new File(codePath);
9381        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
9382        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
9383
9384        info.nativeLibraryRootDir = null;
9385        info.nativeLibraryRootRequiresIsa = false;
9386        info.nativeLibraryDir = null;
9387        info.secondaryNativeLibraryDir = null;
9388
9389        if (isApkFile(codeFile)) {
9390            // Monolithic install
9391            if (bundledApp) {
9392                // If "/system/lib64/apkname" exists, assume that is the per-package
9393                // native library directory to use; otherwise use "/system/lib/apkname".
9394                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
9395                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
9396                        getPrimaryInstructionSet(info));
9397
9398                // This is a bundled system app so choose the path based on the ABI.
9399                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
9400                // is just the default path.
9401                final String apkName = deriveCodePathName(codePath);
9402                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
9403                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
9404                        apkName).getAbsolutePath();
9405
9406                if (info.secondaryCpuAbi != null) {
9407                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
9408                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
9409                            secondaryLibDir, apkName).getAbsolutePath();
9410                }
9411            } else if (asecApp) {
9412                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
9413                        .getAbsolutePath();
9414            } else {
9415                final String apkName = deriveCodePathName(codePath);
9416                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
9417                        .getAbsolutePath();
9418            }
9419
9420            info.nativeLibraryRootRequiresIsa = false;
9421            info.nativeLibraryDir = info.nativeLibraryRootDir;
9422        } else {
9423            // Cluster install
9424            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
9425            info.nativeLibraryRootRequiresIsa = true;
9426
9427            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
9428                    getPrimaryInstructionSet(info)).getAbsolutePath();
9429
9430            if (info.secondaryCpuAbi != null) {
9431                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
9432                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
9433            }
9434        }
9435    }
9436
9437    /**
9438     * Calculate the abis and roots for a bundled app. These can uniquely
9439     * be determined from the contents of the system partition, i.e whether
9440     * it contains 64 or 32 bit shared libraries etc. We do not validate any
9441     * of this information, and instead assume that the system was built
9442     * sensibly.
9443     */
9444    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
9445                                           PackageSetting pkgSetting) {
9446        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
9447
9448        // If "/system/lib64/apkname" exists, assume that is the per-package
9449        // native library directory to use; otherwise use "/system/lib/apkname".
9450        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
9451        setBundledAppAbi(pkg, apkRoot, apkName);
9452        // pkgSetting might be null during rescan following uninstall of updates
9453        // to a bundled app, so accommodate that possibility.  The settings in
9454        // that case will be established later from the parsed package.
9455        //
9456        // If the settings aren't null, sync them up with what we've just derived.
9457        // note that apkRoot isn't stored in the package settings.
9458        if (pkgSetting != null) {
9459            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
9460            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
9461        }
9462    }
9463
9464    /**
9465     * Deduces the ABI of a bundled app and sets the relevant fields on the
9466     * parsed pkg object.
9467     *
9468     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
9469     *        under which system libraries are installed.
9470     * @param apkName the name of the installed package.
9471     */
9472    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
9473        final File codeFile = new File(pkg.codePath);
9474
9475        final boolean has64BitLibs;
9476        final boolean has32BitLibs;
9477        if (isApkFile(codeFile)) {
9478            // Monolithic install
9479            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
9480            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
9481        } else {
9482            // Cluster install
9483            final File rootDir = new File(codeFile, LIB_DIR_NAME);
9484            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
9485                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
9486                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
9487                has64BitLibs = (new File(rootDir, isa)).exists();
9488            } else {
9489                has64BitLibs = false;
9490            }
9491            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
9492                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
9493                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
9494                has32BitLibs = (new File(rootDir, isa)).exists();
9495            } else {
9496                has32BitLibs = false;
9497            }
9498        }
9499
9500        if (has64BitLibs && !has32BitLibs) {
9501            // The package has 64 bit libs, but not 32 bit libs. Its primary
9502            // ABI should be 64 bit. We can safely assume here that the bundled
9503            // native libraries correspond to the most preferred ABI in the list.
9504
9505            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9506            pkg.applicationInfo.secondaryCpuAbi = null;
9507        } else if (has32BitLibs && !has64BitLibs) {
9508            // The package has 32 bit libs but not 64 bit libs. Its primary
9509            // ABI should be 32 bit.
9510
9511            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9512            pkg.applicationInfo.secondaryCpuAbi = null;
9513        } else if (has32BitLibs && has64BitLibs) {
9514            // The application has both 64 and 32 bit bundled libraries. We check
9515            // here that the app declares multiArch support, and warn if it doesn't.
9516            //
9517            // We will be lenient here and record both ABIs. The primary will be the
9518            // ABI that's higher on the list, i.e, a device that's configured to prefer
9519            // 64 bit apps will see a 64 bit primary ABI,
9520
9521            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
9522                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
9523            }
9524
9525            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
9526                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9527                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9528            } else {
9529                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
9530                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
9531            }
9532        } else {
9533            pkg.applicationInfo.primaryCpuAbi = null;
9534            pkg.applicationInfo.secondaryCpuAbi = null;
9535        }
9536    }
9537
9538    private void killApplication(String pkgName, int appId, String reason) {
9539        // Request the ActivityManager to kill the process(only for existing packages)
9540        // so that we do not end up in a confused state while the user is still using the older
9541        // version of the application while the new one gets installed.
9542        final long token = Binder.clearCallingIdentity();
9543        try {
9544            IActivityManager am = ActivityManagerNative.getDefault();
9545            if (am != null) {
9546                try {
9547                    am.killApplicationWithAppId(pkgName, appId, reason);
9548                } catch (RemoteException e) {
9549                }
9550            }
9551        } finally {
9552            Binder.restoreCallingIdentity(token);
9553        }
9554    }
9555
9556    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
9557        // Remove the parent package setting
9558        PackageSetting ps = (PackageSetting) pkg.mExtras;
9559        if (ps != null) {
9560            removePackageLI(ps, chatty);
9561        }
9562        // Remove the child package setting
9563        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9564        for (int i = 0; i < childCount; i++) {
9565            PackageParser.Package childPkg = pkg.childPackages.get(i);
9566            ps = (PackageSetting) childPkg.mExtras;
9567            if (ps != null) {
9568                removePackageLI(ps, chatty);
9569            }
9570        }
9571    }
9572
9573    void removePackageLI(PackageSetting ps, boolean chatty) {
9574        if (DEBUG_INSTALL) {
9575            if (chatty)
9576                Log.d(TAG, "Removing package " + ps.name);
9577        }
9578
9579        // writer
9580        synchronized (mPackages) {
9581            mPackages.remove(ps.name);
9582            final PackageParser.Package pkg = ps.pkg;
9583            if (pkg != null) {
9584                cleanPackageDataStructuresLILPw(pkg, chatty);
9585            }
9586        }
9587    }
9588
9589    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9590        if (DEBUG_INSTALL) {
9591            if (chatty)
9592                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9593        }
9594
9595        // writer
9596        synchronized (mPackages) {
9597            // Remove the parent package
9598            mPackages.remove(pkg.applicationInfo.packageName);
9599            cleanPackageDataStructuresLILPw(pkg, chatty);
9600
9601            // Remove the child packages
9602            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9603            for (int i = 0; i < childCount; i++) {
9604                PackageParser.Package childPkg = pkg.childPackages.get(i);
9605                mPackages.remove(childPkg.applicationInfo.packageName);
9606                cleanPackageDataStructuresLILPw(childPkg, chatty);
9607            }
9608        }
9609    }
9610
9611    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9612        int N = pkg.providers.size();
9613        StringBuilder r = null;
9614        int i;
9615        for (i=0; i<N; i++) {
9616            PackageParser.Provider p = pkg.providers.get(i);
9617            mProviders.removeProvider(p);
9618            if (p.info.authority == null) {
9619
9620                /* There was another ContentProvider with this authority when
9621                 * this app was installed so this authority is null,
9622                 * Ignore it as we don't have to unregister the provider.
9623                 */
9624                continue;
9625            }
9626            String names[] = p.info.authority.split(";");
9627            for (int j = 0; j < names.length; j++) {
9628                if (mProvidersByAuthority.get(names[j]) == p) {
9629                    mProvidersByAuthority.remove(names[j]);
9630                    if (DEBUG_REMOVE) {
9631                        if (chatty)
9632                            Log.d(TAG, "Unregistered content provider: " + names[j]
9633                                    + ", className = " + p.info.name + ", isSyncable = "
9634                                    + p.info.isSyncable);
9635                    }
9636                }
9637            }
9638            if (DEBUG_REMOVE && chatty) {
9639                if (r == null) {
9640                    r = new StringBuilder(256);
9641                } else {
9642                    r.append(' ');
9643                }
9644                r.append(p.info.name);
9645            }
9646        }
9647        if (r != null) {
9648            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9649        }
9650
9651        N = pkg.services.size();
9652        r = null;
9653        for (i=0; i<N; i++) {
9654            PackageParser.Service s = pkg.services.get(i);
9655            mServices.removeService(s);
9656            if (chatty) {
9657                if (r == null) {
9658                    r = new StringBuilder(256);
9659                } else {
9660                    r.append(' ');
9661                }
9662                r.append(s.info.name);
9663            }
9664        }
9665        if (r != null) {
9666            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9667        }
9668
9669        N = pkg.receivers.size();
9670        r = null;
9671        for (i=0; i<N; i++) {
9672            PackageParser.Activity a = pkg.receivers.get(i);
9673            mReceivers.removeActivity(a, "receiver");
9674            if (DEBUG_REMOVE && chatty) {
9675                if (r == null) {
9676                    r = new StringBuilder(256);
9677                } else {
9678                    r.append(' ');
9679                }
9680                r.append(a.info.name);
9681            }
9682        }
9683        if (r != null) {
9684            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9685        }
9686
9687        N = pkg.activities.size();
9688        r = null;
9689        for (i=0; i<N; i++) {
9690            PackageParser.Activity a = pkg.activities.get(i);
9691            mActivities.removeActivity(a, "activity");
9692            if (DEBUG_REMOVE && chatty) {
9693                if (r == null) {
9694                    r = new StringBuilder(256);
9695                } else {
9696                    r.append(' ');
9697                }
9698                r.append(a.info.name);
9699            }
9700        }
9701        if (r != null) {
9702            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9703        }
9704
9705        N = pkg.permissions.size();
9706        r = null;
9707        for (i=0; i<N; i++) {
9708            PackageParser.Permission p = pkg.permissions.get(i);
9709            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9710            if (bp == null) {
9711                bp = mSettings.mPermissionTrees.get(p.info.name);
9712            }
9713            if (bp != null && bp.perm == p) {
9714                bp.perm = null;
9715                if (DEBUG_REMOVE && chatty) {
9716                    if (r == null) {
9717                        r = new StringBuilder(256);
9718                    } else {
9719                        r.append(' ');
9720                    }
9721                    r.append(p.info.name);
9722                }
9723            }
9724            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9725                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9726                if (appOpPkgs != null) {
9727                    appOpPkgs.remove(pkg.packageName);
9728                }
9729            }
9730        }
9731        if (r != null) {
9732            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9733        }
9734
9735        N = pkg.requestedPermissions.size();
9736        r = null;
9737        for (i=0; i<N; i++) {
9738            String perm = pkg.requestedPermissions.get(i);
9739            BasePermission bp = mSettings.mPermissions.get(perm);
9740            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9741                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9742                if (appOpPkgs != null) {
9743                    appOpPkgs.remove(pkg.packageName);
9744                    if (appOpPkgs.isEmpty()) {
9745                        mAppOpPermissionPackages.remove(perm);
9746                    }
9747                }
9748            }
9749        }
9750        if (r != null) {
9751            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9752        }
9753
9754        N = pkg.instrumentation.size();
9755        r = null;
9756        for (i=0; i<N; i++) {
9757            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9758            mInstrumentation.remove(a.getComponentName());
9759            if (DEBUG_REMOVE && chatty) {
9760                if (r == null) {
9761                    r = new StringBuilder(256);
9762                } else {
9763                    r.append(' ');
9764                }
9765                r.append(a.info.name);
9766            }
9767        }
9768        if (r != null) {
9769            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9770        }
9771
9772        r = null;
9773        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9774            // Only system apps can hold shared libraries.
9775            if (pkg.libraryNames != null) {
9776                for (i=0; i<pkg.libraryNames.size(); i++) {
9777                    String name = pkg.libraryNames.get(i);
9778                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9779                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9780                        mSharedLibraries.remove(name);
9781                        if (DEBUG_REMOVE && chatty) {
9782                            if (r == null) {
9783                                r = new StringBuilder(256);
9784                            } else {
9785                                r.append(' ');
9786                            }
9787                            r.append(name);
9788                        }
9789                    }
9790                }
9791            }
9792        }
9793        if (r != null) {
9794            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9795        }
9796    }
9797
9798    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9799        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9800            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9801                return true;
9802            }
9803        }
9804        return false;
9805    }
9806
9807    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9808    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9809    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9810
9811    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9812        // Update the parent permissions
9813        updatePermissionsLPw(pkg.packageName, pkg, flags);
9814        // Update the child permissions
9815        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9816        for (int i = 0; i < childCount; i++) {
9817            PackageParser.Package childPkg = pkg.childPackages.get(i);
9818            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9819        }
9820    }
9821
9822    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9823            int flags) {
9824        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9825        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9826    }
9827
9828    private void updatePermissionsLPw(String changingPkg,
9829            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9830        // Make sure there are no dangling permission trees.
9831        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9832        while (it.hasNext()) {
9833            final BasePermission bp = it.next();
9834            if (bp.packageSetting == null) {
9835                // We may not yet have parsed the package, so just see if
9836                // we still know about its settings.
9837                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9838            }
9839            if (bp.packageSetting == null) {
9840                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9841                        + " from package " + bp.sourcePackage);
9842                it.remove();
9843            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9844                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9845                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9846                            + " from package " + bp.sourcePackage);
9847                    flags |= UPDATE_PERMISSIONS_ALL;
9848                    it.remove();
9849                }
9850            }
9851        }
9852
9853        // Make sure all dynamic permissions have been assigned to a package,
9854        // and make sure there are no dangling permissions.
9855        it = mSettings.mPermissions.values().iterator();
9856        while (it.hasNext()) {
9857            final BasePermission bp = it.next();
9858            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9859                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9860                        + bp.name + " pkg=" + bp.sourcePackage
9861                        + " info=" + bp.pendingInfo);
9862                if (bp.packageSetting == null && bp.pendingInfo != null) {
9863                    final BasePermission tree = findPermissionTreeLP(bp.name);
9864                    if (tree != null && tree.perm != null) {
9865                        bp.packageSetting = tree.packageSetting;
9866                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9867                                new PermissionInfo(bp.pendingInfo));
9868                        bp.perm.info.packageName = tree.perm.info.packageName;
9869                        bp.perm.info.name = bp.name;
9870                        bp.uid = tree.uid;
9871                    }
9872                }
9873            }
9874            if (bp.packageSetting == null) {
9875                // We may not yet have parsed the package, so just see if
9876                // we still know about its settings.
9877                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9878            }
9879            if (bp.packageSetting == null) {
9880                Slog.w(TAG, "Removing dangling permission: " + bp.name
9881                        + " from package " + bp.sourcePackage);
9882                it.remove();
9883            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9884                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9885                    Slog.i(TAG, "Removing old permission: " + bp.name
9886                            + " from package " + bp.sourcePackage);
9887                    flags |= UPDATE_PERMISSIONS_ALL;
9888                    it.remove();
9889                }
9890            }
9891        }
9892
9893        // Now update the permissions for all packages, in particular
9894        // replace the granted permissions of the system packages.
9895        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9896            for (PackageParser.Package pkg : mPackages.values()) {
9897                if (pkg != pkgInfo) {
9898                    // Only replace for packages on requested volume
9899                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9900                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9901                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9902                    grantPermissionsLPw(pkg, replace, changingPkg);
9903                }
9904            }
9905        }
9906
9907        if (pkgInfo != null) {
9908            // Only replace for packages on requested volume
9909            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9910            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9911                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9912            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9913        }
9914    }
9915
9916    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9917            String packageOfInterest) {
9918        // IMPORTANT: There are two types of permissions: install and runtime.
9919        // Install time permissions are granted when the app is installed to
9920        // all device users and users added in the future. Runtime permissions
9921        // are granted at runtime explicitly to specific users. Normal and signature
9922        // protected permissions are install time permissions. Dangerous permissions
9923        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9924        // otherwise they are runtime permissions. This function does not manage
9925        // runtime permissions except for the case an app targeting Lollipop MR1
9926        // being upgraded to target a newer SDK, in which case dangerous permissions
9927        // are transformed from install time to runtime ones.
9928
9929        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9930        if (ps == null) {
9931            return;
9932        }
9933
9934        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9935
9936        PermissionsState permissionsState = ps.getPermissionsState();
9937        PermissionsState origPermissions = permissionsState;
9938
9939        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9940
9941        boolean runtimePermissionsRevoked = false;
9942        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9943
9944        boolean changedInstallPermission = false;
9945
9946        if (replace) {
9947            ps.installPermissionsFixed = false;
9948            if (!ps.isSharedUser()) {
9949                origPermissions = new PermissionsState(permissionsState);
9950                permissionsState.reset();
9951            } else {
9952                // We need to know only about runtime permission changes since the
9953                // calling code always writes the install permissions state but
9954                // the runtime ones are written only if changed. The only cases of
9955                // changed runtime permissions here are promotion of an install to
9956                // runtime and revocation of a runtime from a shared user.
9957                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9958                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9959                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9960                    runtimePermissionsRevoked = true;
9961                }
9962            }
9963        }
9964
9965        permissionsState.setGlobalGids(mGlobalGids);
9966
9967        final int N = pkg.requestedPermissions.size();
9968        for (int i=0; i<N; i++) {
9969            final String name = pkg.requestedPermissions.get(i);
9970            final BasePermission bp = mSettings.mPermissions.get(name);
9971
9972            if (DEBUG_INSTALL) {
9973                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9974            }
9975
9976            if (bp == null || bp.packageSetting == null) {
9977                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9978                    Slog.w(TAG, "Unknown permission " + name
9979                            + " in package " + pkg.packageName);
9980                }
9981                continue;
9982            }
9983
9984            final String perm = bp.name;
9985            boolean allowedSig = false;
9986            int grant = GRANT_DENIED;
9987
9988            // Keep track of app op permissions.
9989            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9990                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9991                if (pkgs == null) {
9992                    pkgs = new ArraySet<>();
9993                    mAppOpPermissionPackages.put(bp.name, pkgs);
9994                }
9995                pkgs.add(pkg.packageName);
9996            }
9997
9998            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9999            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
10000                    >= Build.VERSION_CODES.M;
10001            switch (level) {
10002                case PermissionInfo.PROTECTION_NORMAL: {
10003                    // For all apps normal permissions are install time ones.
10004                    grant = GRANT_INSTALL;
10005                } break;
10006
10007                case PermissionInfo.PROTECTION_DANGEROUS: {
10008                    // If a permission review is required for legacy apps we represent
10009                    // their permissions as always granted runtime ones since we need
10010                    // to keep the review required permission flag per user while an
10011                    // install permission's state is shared across all users.
10012                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
10013                        // For legacy apps dangerous permissions are install time ones.
10014                        grant = GRANT_INSTALL;
10015                    } else if (origPermissions.hasInstallPermission(bp.name)) {
10016                        // For legacy apps that became modern, install becomes runtime.
10017                        grant = GRANT_UPGRADE;
10018                    } else if (mPromoteSystemApps
10019                            && isSystemApp(ps)
10020                            && mExistingSystemPackages.contains(ps.name)) {
10021                        // For legacy system apps, install becomes runtime.
10022                        // We cannot check hasInstallPermission() for system apps since those
10023                        // permissions were granted implicitly and not persisted pre-M.
10024                        grant = GRANT_UPGRADE;
10025                    } else {
10026                        // For modern apps keep runtime permissions unchanged.
10027                        grant = GRANT_RUNTIME;
10028                    }
10029                } break;
10030
10031                case PermissionInfo.PROTECTION_SIGNATURE: {
10032                    // For all apps signature permissions are install time ones.
10033                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
10034                    if (allowedSig) {
10035                        grant = GRANT_INSTALL;
10036                    }
10037                } break;
10038            }
10039
10040            if (DEBUG_INSTALL) {
10041                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
10042            }
10043
10044            if (grant != GRANT_DENIED) {
10045                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
10046                    // If this is an existing, non-system package, then
10047                    // we can't add any new permissions to it.
10048                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
10049                        // Except...  if this is a permission that was added
10050                        // to the platform (note: need to only do this when
10051                        // updating the platform).
10052                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
10053                            grant = GRANT_DENIED;
10054                        }
10055                    }
10056                }
10057
10058                switch (grant) {
10059                    case GRANT_INSTALL: {
10060                        // Revoke this as runtime permission to handle the case of
10061                        // a runtime permission being downgraded to an install one.
10062                        // Also in permission review mode we keep dangerous permissions
10063                        // for legacy apps
10064                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10065                            if (origPermissions.getRuntimePermissionState(
10066                                    bp.name, userId) != null) {
10067                                // Revoke the runtime permission and clear the flags.
10068                                origPermissions.revokeRuntimePermission(bp, userId);
10069                                origPermissions.updatePermissionFlags(bp, userId,
10070                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
10071                                // If we revoked a permission permission, we have to write.
10072                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10073                                        changedRuntimePermissionUserIds, userId);
10074                            }
10075                        }
10076                        // Grant an install permission.
10077                        if (permissionsState.grantInstallPermission(bp) !=
10078                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
10079                            changedInstallPermission = true;
10080                        }
10081                    } break;
10082
10083                    case GRANT_RUNTIME: {
10084                        // Grant previously granted runtime permissions.
10085                        for (int userId : UserManagerService.getInstance().getUserIds()) {
10086                            PermissionState permissionState = origPermissions
10087                                    .getRuntimePermissionState(bp.name, userId);
10088                            int flags = permissionState != null
10089                                    ? permissionState.getFlags() : 0;
10090                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
10091                                if (permissionsState.grantRuntimePermission(bp, userId) ==
10092                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10093                                    // If we cannot put the permission as it was, we have to write.
10094                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10095                                            changedRuntimePermissionUserIds, userId);
10096                                }
10097                                // If the app supports runtime permissions no need for a review.
10098                                if (Build.PERMISSIONS_REVIEW_REQUIRED
10099                                        && appSupportsRuntimePermissions
10100                                        && (flags & PackageManager
10101                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
10102                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
10103                                    // Since we changed the flags, we have to write.
10104                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10105                                            changedRuntimePermissionUserIds, userId);
10106                                }
10107                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
10108                                    && !appSupportsRuntimePermissions) {
10109                                // For legacy apps that need a permission review, every new
10110                                // runtime permission is granted but it is pending a review.
10111                                // We also need to review only platform defined runtime
10112                                // permissions as these are the only ones the platform knows
10113                                // how to disable the API to simulate revocation as legacy
10114                                // apps don't expect to run with revoked permissions.
10115                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
10116                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
10117                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
10118                                        // We changed the flags, hence have to write.
10119                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10120                                                changedRuntimePermissionUserIds, userId);
10121                                    }
10122                                }
10123                                if (permissionsState.grantRuntimePermission(bp, userId)
10124                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10125                                    // We changed the permission, hence have to write.
10126                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10127                                            changedRuntimePermissionUserIds, userId);
10128                                }
10129                            }
10130                            // Propagate the permission flags.
10131                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
10132                        }
10133                    } break;
10134
10135                    case GRANT_UPGRADE: {
10136                        // Grant runtime permissions for a previously held install permission.
10137                        PermissionState permissionState = origPermissions
10138                                .getInstallPermissionState(bp.name);
10139                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
10140
10141                        if (origPermissions.revokeInstallPermission(bp)
10142                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
10143                            // We will be transferring the permission flags, so clear them.
10144                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
10145                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
10146                            changedInstallPermission = true;
10147                        }
10148
10149                        // If the permission is not to be promoted to runtime we ignore it and
10150                        // also its other flags as they are not applicable to install permissions.
10151                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
10152                            for (int userId : currentUserIds) {
10153                                if (permissionsState.grantRuntimePermission(bp, userId) !=
10154                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10155                                    // Transfer the permission flags.
10156                                    permissionsState.updatePermissionFlags(bp, userId,
10157                                            flags, flags);
10158                                    // If we granted the permission, we have to write.
10159                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
10160                                            changedRuntimePermissionUserIds, userId);
10161                                }
10162                            }
10163                        }
10164                    } break;
10165
10166                    default: {
10167                        if (packageOfInterest == null
10168                                || packageOfInterest.equals(pkg.packageName)) {
10169                            Slog.w(TAG, "Not granting permission " + perm
10170                                    + " to package " + pkg.packageName
10171                                    + " because it was previously installed without");
10172                        }
10173                    } break;
10174                }
10175            } else {
10176                if (permissionsState.revokeInstallPermission(bp) !=
10177                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
10178                    // Also drop the permission flags.
10179                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
10180                            PackageManager.MASK_PERMISSION_FLAGS, 0);
10181                    changedInstallPermission = true;
10182                    Slog.i(TAG, "Un-granting permission " + perm
10183                            + " from package " + pkg.packageName
10184                            + " (protectionLevel=" + bp.protectionLevel
10185                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10186                            + ")");
10187                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
10188                    // Don't print warning for app op permissions, since it is fine for them
10189                    // not to be granted, there is a UI for the user to decide.
10190                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
10191                        Slog.w(TAG, "Not granting permission " + perm
10192                                + " to package " + pkg.packageName
10193                                + " (protectionLevel=" + bp.protectionLevel
10194                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
10195                                + ")");
10196                    }
10197                }
10198            }
10199        }
10200
10201        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
10202                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
10203            // This is the first that we have heard about this package, so the
10204            // permissions we have now selected are fixed until explicitly
10205            // changed.
10206            ps.installPermissionsFixed = true;
10207        }
10208
10209        // Persist the runtime permissions state for users with changes. If permissions
10210        // were revoked because no app in the shared user declares them we have to
10211        // write synchronously to avoid losing runtime permissions state.
10212        for (int userId : changedRuntimePermissionUserIds) {
10213            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
10214        }
10215
10216        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10217    }
10218
10219    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
10220        boolean allowed = false;
10221        final int NP = PackageParser.NEW_PERMISSIONS.length;
10222        for (int ip=0; ip<NP; ip++) {
10223            final PackageParser.NewPermissionInfo npi
10224                    = PackageParser.NEW_PERMISSIONS[ip];
10225            if (npi.name.equals(perm)
10226                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
10227                allowed = true;
10228                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
10229                        + pkg.packageName);
10230                break;
10231            }
10232        }
10233        return allowed;
10234    }
10235
10236    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
10237            BasePermission bp, PermissionsState origPermissions) {
10238        boolean allowed;
10239        allowed = (compareSignatures(
10240                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
10241                        == PackageManager.SIGNATURE_MATCH)
10242                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
10243                        == PackageManager.SIGNATURE_MATCH);
10244        if (!allowed && (bp.protectionLevel
10245                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
10246            if (isSystemApp(pkg)) {
10247                // For updated system applications, a system permission
10248                // is granted only if it had been defined by the original application.
10249                if (pkg.isUpdatedSystemApp()) {
10250                    final PackageSetting sysPs = mSettings
10251                            .getDisabledSystemPkgLPr(pkg.packageName);
10252                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
10253                        // If the original was granted this permission, we take
10254                        // that grant decision as read and propagate it to the
10255                        // update.
10256                        if (sysPs.isPrivileged()) {
10257                            allowed = true;
10258                        }
10259                    } else {
10260                        // The system apk may have been updated with an older
10261                        // version of the one on the data partition, but which
10262                        // granted a new system permission that it didn't have
10263                        // before.  In this case we do want to allow the app to
10264                        // now get the new permission if the ancestral apk is
10265                        // privileged to get it.
10266                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
10267                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
10268                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
10269                                    allowed = true;
10270                                    break;
10271                                }
10272                            }
10273                        }
10274                        // Also if a privileged parent package on the system image or any of
10275                        // its children requested a privileged permission, the updated child
10276                        // packages can also get the permission.
10277                        if (pkg.parentPackage != null) {
10278                            final PackageSetting disabledSysParentPs = mSettings
10279                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
10280                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
10281                                    && disabledSysParentPs.isPrivileged()) {
10282                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
10283                                    allowed = true;
10284                                } else if (disabledSysParentPs.pkg.childPackages != null) {
10285                                    final int count = disabledSysParentPs.pkg.childPackages.size();
10286                                    for (int i = 0; i < count; i++) {
10287                                        PackageParser.Package disabledSysChildPkg =
10288                                                disabledSysParentPs.pkg.childPackages.get(i);
10289                                        if (isPackageRequestingPermission(disabledSysChildPkg,
10290                                                perm)) {
10291                                            allowed = true;
10292                                            break;
10293                                        }
10294                                    }
10295                                }
10296                            }
10297                        }
10298                    }
10299                } else {
10300                    allowed = isPrivilegedApp(pkg);
10301                }
10302            }
10303        }
10304        if (!allowed) {
10305            if (!allowed && (bp.protectionLevel
10306                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
10307                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
10308                // If this was a previously normal/dangerous permission that got moved
10309                // to a system permission as part of the runtime permission redesign, then
10310                // we still want to blindly grant it to old apps.
10311                allowed = true;
10312            }
10313            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
10314                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
10315                // If this permission is to be granted to the system installer and
10316                // this app is an installer, then it gets the permission.
10317                allowed = true;
10318            }
10319            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
10320                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
10321                // If this permission is to be granted to the system verifier and
10322                // this app is a verifier, then it gets the permission.
10323                allowed = true;
10324            }
10325            if (!allowed && (bp.protectionLevel
10326                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
10327                    && isSystemApp(pkg)) {
10328                // Any pre-installed system app is allowed to get this permission.
10329                allowed = true;
10330            }
10331            if (!allowed && (bp.protectionLevel
10332                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
10333                // For development permissions, a development permission
10334                // is granted only if it was already granted.
10335                allowed = origPermissions.hasInstallPermission(perm);
10336            }
10337            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
10338                    && pkg.packageName.equals(mSetupWizardPackage)) {
10339                // If this permission is to be granted to the system setup wizard and
10340                // this app is a setup wizard, then it gets the permission.
10341                allowed = true;
10342            }
10343        }
10344        return allowed;
10345    }
10346
10347    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
10348        final int permCount = pkg.requestedPermissions.size();
10349        for (int j = 0; j < permCount; j++) {
10350            String requestedPermission = pkg.requestedPermissions.get(j);
10351            if (permission.equals(requestedPermission)) {
10352                return true;
10353            }
10354        }
10355        return false;
10356    }
10357
10358    final class ActivityIntentResolver
10359            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
10360        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10361                boolean defaultOnly, int userId) {
10362            if (!sUserManager.exists(userId)) return null;
10363            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10364            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10365        }
10366
10367        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10368                int userId) {
10369            if (!sUserManager.exists(userId)) return null;
10370            mFlags = flags;
10371            return super.queryIntent(intent, resolvedType,
10372                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10373        }
10374
10375        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10376                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
10377            if (!sUserManager.exists(userId)) return null;
10378            if (packageActivities == null) {
10379                return null;
10380            }
10381            mFlags = flags;
10382            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10383            final int N = packageActivities.size();
10384            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
10385                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
10386
10387            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
10388            for (int i = 0; i < N; ++i) {
10389                intentFilters = packageActivities.get(i).intents;
10390                if (intentFilters != null && intentFilters.size() > 0) {
10391                    PackageParser.ActivityIntentInfo[] array =
10392                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
10393                    intentFilters.toArray(array);
10394                    listCut.add(array);
10395                }
10396            }
10397            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10398        }
10399
10400        /**
10401         * Finds a privileged activity that matches the specified activity names.
10402         */
10403        private PackageParser.Activity findMatchingActivity(
10404                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
10405            for (PackageParser.Activity sysActivity : activityList) {
10406                if (sysActivity.info.name.equals(activityInfo.name)) {
10407                    return sysActivity;
10408                }
10409                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
10410                    return sysActivity;
10411                }
10412                if (sysActivity.info.targetActivity != null) {
10413                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
10414                        return sysActivity;
10415                    }
10416                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
10417                        return sysActivity;
10418                    }
10419                }
10420            }
10421            return null;
10422        }
10423
10424        public class IterGenerator<E> {
10425            public Iterator<E> generate(ActivityIntentInfo info) {
10426                return null;
10427            }
10428        }
10429
10430        public class ActionIterGenerator extends IterGenerator<String> {
10431            @Override
10432            public Iterator<String> generate(ActivityIntentInfo info) {
10433                return info.actionsIterator();
10434            }
10435        }
10436
10437        public class CategoriesIterGenerator extends IterGenerator<String> {
10438            @Override
10439            public Iterator<String> generate(ActivityIntentInfo info) {
10440                return info.categoriesIterator();
10441            }
10442        }
10443
10444        public class SchemesIterGenerator extends IterGenerator<String> {
10445            @Override
10446            public Iterator<String> generate(ActivityIntentInfo info) {
10447                return info.schemesIterator();
10448            }
10449        }
10450
10451        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
10452            @Override
10453            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
10454                return info.authoritiesIterator();
10455            }
10456        }
10457
10458        /**
10459         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
10460         * MODIFIED. Do not pass in a list that should not be changed.
10461         */
10462        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
10463                IterGenerator<T> generator, Iterator<T> searchIterator) {
10464            // loop through the set of actions; every one must be found in the intent filter
10465            while (searchIterator.hasNext()) {
10466                // we must have at least one filter in the list to consider a match
10467                if (intentList.size() == 0) {
10468                    break;
10469                }
10470
10471                final T searchAction = searchIterator.next();
10472
10473                // loop through the set of intent filters
10474                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
10475                while (intentIter.hasNext()) {
10476                    final ActivityIntentInfo intentInfo = intentIter.next();
10477                    boolean selectionFound = false;
10478
10479                    // loop through the intent filter's selection criteria; at least one
10480                    // of them must match the searched criteria
10481                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
10482                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
10483                        final T intentSelection = intentSelectionIter.next();
10484                        if (intentSelection != null && intentSelection.equals(searchAction)) {
10485                            selectionFound = true;
10486                            break;
10487                        }
10488                    }
10489
10490                    // the selection criteria wasn't found in this filter's set; this filter
10491                    // is not a potential match
10492                    if (!selectionFound) {
10493                        intentIter.remove();
10494                    }
10495                }
10496            }
10497        }
10498
10499        private boolean isProtectedAction(ActivityIntentInfo filter) {
10500            final Iterator<String> actionsIter = filter.actionsIterator();
10501            while (actionsIter != null && actionsIter.hasNext()) {
10502                final String filterAction = actionsIter.next();
10503                if (PROTECTED_ACTIONS.contains(filterAction)) {
10504                    return true;
10505                }
10506            }
10507            return false;
10508        }
10509
10510        /**
10511         * Adjusts the priority of the given intent filter according to policy.
10512         * <p>
10513         * <ul>
10514         * <li>The priority for non privileged applications is capped to '0'</li>
10515         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
10516         * <li>The priority for unbundled updates to privileged applications is capped to the
10517         *      priority defined on the system partition</li>
10518         * </ul>
10519         * <p>
10520         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
10521         * allowed to obtain any priority on any action.
10522         */
10523        private void adjustPriority(
10524                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
10525            // nothing to do; priority is fine as-is
10526            if (intent.getPriority() <= 0) {
10527                return;
10528            }
10529
10530            final ActivityInfo activityInfo = intent.activity.info;
10531            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
10532
10533            final boolean privilegedApp =
10534                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
10535            if (!privilegedApp) {
10536                // non-privileged applications can never define a priority >0
10537                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
10538                        + " package: " + applicationInfo.packageName
10539                        + " activity: " + intent.activity.className
10540                        + " origPrio: " + intent.getPriority());
10541                intent.setPriority(0);
10542                return;
10543            }
10544
10545            if (systemActivities == null) {
10546                // the system package is not disabled; we're parsing the system partition
10547                if (isProtectedAction(intent)) {
10548                    if (mDeferProtectedFilters) {
10549                        // We can't deal with these just yet. No component should ever obtain a
10550                        // >0 priority for a protected actions, with ONE exception -- the setup
10551                        // wizard. The setup wizard, however, cannot be known until we're able to
10552                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
10553                        // until all intent filters have been processed. Chicken, meet egg.
10554                        // Let the filter temporarily have a high priority and rectify the
10555                        // priorities after all system packages have been scanned.
10556                        mProtectedFilters.add(intent);
10557                        if (DEBUG_FILTERS) {
10558                            Slog.i(TAG, "Protected action; save for later;"
10559                                    + " package: " + applicationInfo.packageName
10560                                    + " activity: " + intent.activity.className
10561                                    + " origPrio: " + intent.getPriority());
10562                        }
10563                        return;
10564                    } else {
10565                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
10566                            Slog.i(TAG, "No setup wizard;"
10567                                + " All protected intents capped to priority 0");
10568                        }
10569                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
10570                            if (DEBUG_FILTERS) {
10571                                Slog.i(TAG, "Found setup wizard;"
10572                                    + " allow priority " + intent.getPriority() + ";"
10573                                    + " package: " + intent.activity.info.packageName
10574                                    + " activity: " + intent.activity.className
10575                                    + " priority: " + intent.getPriority());
10576                            }
10577                            // setup wizard gets whatever it wants
10578                            return;
10579                        }
10580                        Slog.w(TAG, "Protected action; cap priority to 0;"
10581                                + " package: " + intent.activity.info.packageName
10582                                + " activity: " + intent.activity.className
10583                                + " origPrio: " + intent.getPriority());
10584                        intent.setPriority(0);
10585                        return;
10586                    }
10587                }
10588                // privileged apps on the system image get whatever priority they request
10589                return;
10590            }
10591
10592            // privileged app unbundled update ... try to find the same activity
10593            final PackageParser.Activity foundActivity =
10594                    findMatchingActivity(systemActivities, activityInfo);
10595            if (foundActivity == null) {
10596                // this is a new activity; it cannot obtain >0 priority
10597                if (DEBUG_FILTERS) {
10598                    Slog.i(TAG, "New activity; cap priority to 0;"
10599                            + " package: " + applicationInfo.packageName
10600                            + " activity: " + intent.activity.className
10601                            + " origPrio: " + intent.getPriority());
10602                }
10603                intent.setPriority(0);
10604                return;
10605            }
10606
10607            // found activity, now check for filter equivalence
10608
10609            // a shallow copy is enough; we modify the list, not its contents
10610            final List<ActivityIntentInfo> intentListCopy =
10611                    new ArrayList<>(foundActivity.intents);
10612            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10613
10614            // find matching action subsets
10615            final Iterator<String> actionsIterator = intent.actionsIterator();
10616            if (actionsIterator != null) {
10617                getIntentListSubset(
10618                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10619                if (intentListCopy.size() == 0) {
10620                    // no more intents to match; we're not equivalent
10621                    if (DEBUG_FILTERS) {
10622                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10623                                + " package: " + applicationInfo.packageName
10624                                + " activity: " + intent.activity.className
10625                                + " origPrio: " + intent.getPriority());
10626                    }
10627                    intent.setPriority(0);
10628                    return;
10629                }
10630            }
10631
10632            // find matching category subsets
10633            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10634            if (categoriesIterator != null) {
10635                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10636                        categoriesIterator);
10637                if (intentListCopy.size() == 0) {
10638                    // no more intents to match; we're not equivalent
10639                    if (DEBUG_FILTERS) {
10640                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10641                                + " package: " + applicationInfo.packageName
10642                                + " activity: " + intent.activity.className
10643                                + " origPrio: " + intent.getPriority());
10644                    }
10645                    intent.setPriority(0);
10646                    return;
10647                }
10648            }
10649
10650            // find matching schemes subsets
10651            final Iterator<String> schemesIterator = intent.schemesIterator();
10652            if (schemesIterator != null) {
10653                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10654                        schemesIterator);
10655                if (intentListCopy.size() == 0) {
10656                    // no more intents to match; we're not equivalent
10657                    if (DEBUG_FILTERS) {
10658                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10659                                + " package: " + applicationInfo.packageName
10660                                + " activity: " + intent.activity.className
10661                                + " origPrio: " + intent.getPriority());
10662                    }
10663                    intent.setPriority(0);
10664                    return;
10665                }
10666            }
10667
10668            // find matching authorities subsets
10669            final Iterator<IntentFilter.AuthorityEntry>
10670                    authoritiesIterator = intent.authoritiesIterator();
10671            if (authoritiesIterator != null) {
10672                getIntentListSubset(intentListCopy,
10673                        new AuthoritiesIterGenerator(),
10674                        authoritiesIterator);
10675                if (intentListCopy.size() == 0) {
10676                    // no more intents to match; we're not equivalent
10677                    if (DEBUG_FILTERS) {
10678                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10679                                + " package: " + applicationInfo.packageName
10680                                + " activity: " + intent.activity.className
10681                                + " origPrio: " + intent.getPriority());
10682                    }
10683                    intent.setPriority(0);
10684                    return;
10685                }
10686            }
10687
10688            // we found matching filter(s); app gets the max priority of all intents
10689            int cappedPriority = 0;
10690            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10691                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10692            }
10693            if (intent.getPriority() > cappedPriority) {
10694                if (DEBUG_FILTERS) {
10695                    Slog.i(TAG, "Found matching filter(s);"
10696                            + " cap priority to " + cappedPriority + ";"
10697                            + " package: " + applicationInfo.packageName
10698                            + " activity: " + intent.activity.className
10699                            + " origPrio: " + intent.getPriority());
10700                }
10701                intent.setPriority(cappedPriority);
10702                return;
10703            }
10704            // all this for nothing; the requested priority was <= what was on the system
10705        }
10706
10707        public final void addActivity(PackageParser.Activity a, String type) {
10708            mActivities.put(a.getComponentName(), a);
10709            if (DEBUG_SHOW_INFO)
10710                Log.v(
10711                TAG, "  " + type + " " +
10712                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10713            if (DEBUG_SHOW_INFO)
10714                Log.v(TAG, "    Class=" + a.info.name);
10715            final int NI = a.intents.size();
10716            for (int j=0; j<NI; j++) {
10717                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10718                if ("activity".equals(type)) {
10719                    final PackageSetting ps =
10720                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10721                    final List<PackageParser.Activity> systemActivities =
10722                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10723                    adjustPriority(systemActivities, intent);
10724                }
10725                if (DEBUG_SHOW_INFO) {
10726                    Log.v(TAG, "    IntentFilter:");
10727                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10728                }
10729                if (!intent.debugCheck()) {
10730                    Log.w(TAG, "==> For Activity " + a.info.name);
10731                }
10732                addFilter(intent);
10733            }
10734        }
10735
10736        public final void removeActivity(PackageParser.Activity a, String type) {
10737            mActivities.remove(a.getComponentName());
10738            if (DEBUG_SHOW_INFO) {
10739                Log.v(TAG, "  " + type + " "
10740                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10741                                : a.info.name) + ":");
10742                Log.v(TAG, "    Class=" + a.info.name);
10743            }
10744            final int NI = a.intents.size();
10745            for (int j=0; j<NI; j++) {
10746                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10747                if (DEBUG_SHOW_INFO) {
10748                    Log.v(TAG, "    IntentFilter:");
10749                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10750                }
10751                removeFilter(intent);
10752            }
10753        }
10754
10755        @Override
10756        protected boolean allowFilterResult(
10757                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10758            ActivityInfo filterAi = filter.activity.info;
10759            for (int i=dest.size()-1; i>=0; i--) {
10760                ActivityInfo destAi = dest.get(i).activityInfo;
10761                if (destAi.name == filterAi.name
10762                        && destAi.packageName == filterAi.packageName) {
10763                    return false;
10764                }
10765            }
10766            return true;
10767        }
10768
10769        @Override
10770        protected ActivityIntentInfo[] newArray(int size) {
10771            return new ActivityIntentInfo[size];
10772        }
10773
10774        @Override
10775        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10776            if (!sUserManager.exists(userId)) return true;
10777            PackageParser.Package p = filter.activity.owner;
10778            if (p != null) {
10779                PackageSetting ps = (PackageSetting)p.mExtras;
10780                if (ps != null) {
10781                    // System apps are never considered stopped for purposes of
10782                    // filtering, because there may be no way for the user to
10783                    // actually re-launch them.
10784                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10785                            && ps.getStopped(userId);
10786                }
10787            }
10788            return false;
10789        }
10790
10791        @Override
10792        protected boolean isPackageForFilter(String packageName,
10793                PackageParser.ActivityIntentInfo info) {
10794            return packageName.equals(info.activity.owner.packageName);
10795        }
10796
10797        @Override
10798        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10799                int match, int userId) {
10800            if (!sUserManager.exists(userId)) return null;
10801            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10802                return null;
10803            }
10804            final PackageParser.Activity activity = info.activity;
10805            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10806            if (ps == null) {
10807                return null;
10808            }
10809            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10810                    ps.readUserState(userId), userId);
10811            if (ai == null) {
10812                return null;
10813            }
10814            final ResolveInfo res = new ResolveInfo();
10815            res.activityInfo = ai;
10816            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10817                res.filter = info;
10818            }
10819            if (info != null) {
10820                res.handleAllWebDataURI = info.handleAllWebDataURI();
10821            }
10822            res.priority = info.getPriority();
10823            res.preferredOrder = activity.owner.mPreferredOrder;
10824            //System.out.println("Result: " + res.activityInfo.className +
10825            //                   " = " + res.priority);
10826            res.match = match;
10827            res.isDefault = info.hasDefault;
10828            res.labelRes = info.labelRes;
10829            res.nonLocalizedLabel = info.nonLocalizedLabel;
10830            if (userNeedsBadging(userId)) {
10831                res.noResourceId = true;
10832            } else {
10833                res.icon = info.icon;
10834            }
10835            res.iconResourceId = info.icon;
10836            res.system = res.activityInfo.applicationInfo.isSystemApp();
10837            return res;
10838        }
10839
10840        @Override
10841        protected void sortResults(List<ResolveInfo> results) {
10842            Collections.sort(results, mResolvePrioritySorter);
10843        }
10844
10845        @Override
10846        protected void dumpFilter(PrintWriter out, String prefix,
10847                PackageParser.ActivityIntentInfo filter) {
10848            out.print(prefix); out.print(
10849                    Integer.toHexString(System.identityHashCode(filter.activity)));
10850                    out.print(' ');
10851                    filter.activity.printComponentShortName(out);
10852                    out.print(" filter ");
10853                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10854        }
10855
10856        @Override
10857        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10858            return filter.activity;
10859        }
10860
10861        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10862            PackageParser.Activity activity = (PackageParser.Activity)label;
10863            out.print(prefix); out.print(
10864                    Integer.toHexString(System.identityHashCode(activity)));
10865                    out.print(' ');
10866                    activity.printComponentShortName(out);
10867            if (count > 1) {
10868                out.print(" ("); out.print(count); out.print(" filters)");
10869            }
10870            out.println();
10871        }
10872
10873        // Keys are String (activity class name), values are Activity.
10874        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10875                = new ArrayMap<ComponentName, PackageParser.Activity>();
10876        private int mFlags;
10877    }
10878
10879    private final class ServiceIntentResolver
10880            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10881        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10882                boolean defaultOnly, int userId) {
10883            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10884            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10885        }
10886
10887        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10888                int userId) {
10889            if (!sUserManager.exists(userId)) return null;
10890            mFlags = flags;
10891            return super.queryIntent(intent, resolvedType,
10892                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10893        }
10894
10895        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10896                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10897            if (!sUserManager.exists(userId)) return null;
10898            if (packageServices == null) {
10899                return null;
10900            }
10901            mFlags = flags;
10902            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10903            final int N = packageServices.size();
10904            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10905                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10906
10907            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10908            for (int i = 0; i < N; ++i) {
10909                intentFilters = packageServices.get(i).intents;
10910                if (intentFilters != null && intentFilters.size() > 0) {
10911                    PackageParser.ServiceIntentInfo[] array =
10912                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10913                    intentFilters.toArray(array);
10914                    listCut.add(array);
10915                }
10916            }
10917            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10918        }
10919
10920        public final void addService(PackageParser.Service s) {
10921            mServices.put(s.getComponentName(), s);
10922            if (DEBUG_SHOW_INFO) {
10923                Log.v(TAG, "  "
10924                        + (s.info.nonLocalizedLabel != null
10925                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10926                Log.v(TAG, "    Class=" + s.info.name);
10927            }
10928            final int NI = s.intents.size();
10929            int j;
10930            for (j=0; j<NI; j++) {
10931                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10932                if (DEBUG_SHOW_INFO) {
10933                    Log.v(TAG, "    IntentFilter:");
10934                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10935                }
10936                if (!intent.debugCheck()) {
10937                    Log.w(TAG, "==> For Service " + s.info.name);
10938                }
10939                addFilter(intent);
10940            }
10941        }
10942
10943        public final void removeService(PackageParser.Service s) {
10944            mServices.remove(s.getComponentName());
10945            if (DEBUG_SHOW_INFO) {
10946                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10947                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10948                Log.v(TAG, "    Class=" + s.info.name);
10949            }
10950            final int NI = s.intents.size();
10951            int j;
10952            for (j=0; j<NI; j++) {
10953                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10954                if (DEBUG_SHOW_INFO) {
10955                    Log.v(TAG, "    IntentFilter:");
10956                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10957                }
10958                removeFilter(intent);
10959            }
10960        }
10961
10962        @Override
10963        protected boolean allowFilterResult(
10964                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10965            ServiceInfo filterSi = filter.service.info;
10966            for (int i=dest.size()-1; i>=0; i--) {
10967                ServiceInfo destAi = dest.get(i).serviceInfo;
10968                if (destAi.name == filterSi.name
10969                        && destAi.packageName == filterSi.packageName) {
10970                    return false;
10971                }
10972            }
10973            return true;
10974        }
10975
10976        @Override
10977        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10978            return new PackageParser.ServiceIntentInfo[size];
10979        }
10980
10981        @Override
10982        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10983            if (!sUserManager.exists(userId)) return true;
10984            PackageParser.Package p = filter.service.owner;
10985            if (p != null) {
10986                PackageSetting ps = (PackageSetting)p.mExtras;
10987                if (ps != null) {
10988                    // System apps are never considered stopped for purposes of
10989                    // filtering, because there may be no way for the user to
10990                    // actually re-launch them.
10991                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10992                            && ps.getStopped(userId);
10993                }
10994            }
10995            return false;
10996        }
10997
10998        @Override
10999        protected boolean isPackageForFilter(String packageName,
11000                PackageParser.ServiceIntentInfo info) {
11001            return packageName.equals(info.service.owner.packageName);
11002        }
11003
11004        @Override
11005        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
11006                int match, int userId) {
11007            if (!sUserManager.exists(userId)) return null;
11008            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
11009            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
11010                return null;
11011            }
11012            final PackageParser.Service service = info.service;
11013            PackageSetting ps = (PackageSetting) service.owner.mExtras;
11014            if (ps == null) {
11015                return null;
11016            }
11017            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
11018                    ps.readUserState(userId), userId);
11019            if (si == null) {
11020                return null;
11021            }
11022            final ResolveInfo res = new ResolveInfo();
11023            res.serviceInfo = si;
11024            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
11025                res.filter = filter;
11026            }
11027            res.priority = info.getPriority();
11028            res.preferredOrder = service.owner.mPreferredOrder;
11029            res.match = match;
11030            res.isDefault = info.hasDefault;
11031            res.labelRes = info.labelRes;
11032            res.nonLocalizedLabel = info.nonLocalizedLabel;
11033            res.icon = info.icon;
11034            res.system = res.serviceInfo.applicationInfo.isSystemApp();
11035            return res;
11036        }
11037
11038        @Override
11039        protected void sortResults(List<ResolveInfo> results) {
11040            Collections.sort(results, mResolvePrioritySorter);
11041        }
11042
11043        @Override
11044        protected void dumpFilter(PrintWriter out, String prefix,
11045                PackageParser.ServiceIntentInfo filter) {
11046            out.print(prefix); out.print(
11047                    Integer.toHexString(System.identityHashCode(filter.service)));
11048                    out.print(' ');
11049                    filter.service.printComponentShortName(out);
11050                    out.print(" filter ");
11051                    out.println(Integer.toHexString(System.identityHashCode(filter)));
11052        }
11053
11054        @Override
11055        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
11056            return filter.service;
11057        }
11058
11059        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11060            PackageParser.Service service = (PackageParser.Service)label;
11061            out.print(prefix); out.print(
11062                    Integer.toHexString(System.identityHashCode(service)));
11063                    out.print(' ');
11064                    service.printComponentShortName(out);
11065            if (count > 1) {
11066                out.print(" ("); out.print(count); out.print(" filters)");
11067            }
11068            out.println();
11069        }
11070
11071//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
11072//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
11073//            final List<ResolveInfo> retList = Lists.newArrayList();
11074//            while (i.hasNext()) {
11075//                final ResolveInfo resolveInfo = (ResolveInfo) i;
11076//                if (isEnabledLP(resolveInfo.serviceInfo)) {
11077//                    retList.add(resolveInfo);
11078//                }
11079//            }
11080//            return retList;
11081//        }
11082
11083        // Keys are String (activity class name), values are Activity.
11084        private final ArrayMap<ComponentName, PackageParser.Service> mServices
11085                = new ArrayMap<ComponentName, PackageParser.Service>();
11086        private int mFlags;
11087    };
11088
11089    private final class ProviderIntentResolver
11090            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
11091        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
11092                boolean defaultOnly, int userId) {
11093            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
11094            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
11095        }
11096
11097        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
11098                int userId) {
11099            if (!sUserManager.exists(userId))
11100                return null;
11101            mFlags = flags;
11102            return super.queryIntent(intent, resolvedType,
11103                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
11104        }
11105
11106        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
11107                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
11108            if (!sUserManager.exists(userId))
11109                return null;
11110            if (packageProviders == null) {
11111                return null;
11112            }
11113            mFlags = flags;
11114            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
11115            final int N = packageProviders.size();
11116            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
11117                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
11118
11119            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
11120            for (int i = 0; i < N; ++i) {
11121                intentFilters = packageProviders.get(i).intents;
11122                if (intentFilters != null && intentFilters.size() > 0) {
11123                    PackageParser.ProviderIntentInfo[] array =
11124                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
11125                    intentFilters.toArray(array);
11126                    listCut.add(array);
11127                }
11128            }
11129            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
11130        }
11131
11132        public final void addProvider(PackageParser.Provider p) {
11133            if (mProviders.containsKey(p.getComponentName())) {
11134                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
11135                return;
11136            }
11137
11138            mProviders.put(p.getComponentName(), p);
11139            if (DEBUG_SHOW_INFO) {
11140                Log.v(TAG, "  "
11141                        + (p.info.nonLocalizedLabel != null
11142                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
11143                Log.v(TAG, "    Class=" + p.info.name);
11144            }
11145            final int NI = p.intents.size();
11146            int j;
11147            for (j = 0; j < NI; j++) {
11148                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11149                if (DEBUG_SHOW_INFO) {
11150                    Log.v(TAG, "    IntentFilter:");
11151                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11152                }
11153                if (!intent.debugCheck()) {
11154                    Log.w(TAG, "==> For Provider " + p.info.name);
11155                }
11156                addFilter(intent);
11157            }
11158        }
11159
11160        public final void removeProvider(PackageParser.Provider p) {
11161            mProviders.remove(p.getComponentName());
11162            if (DEBUG_SHOW_INFO) {
11163                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
11164                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
11165                Log.v(TAG, "    Class=" + p.info.name);
11166            }
11167            final int NI = p.intents.size();
11168            int j;
11169            for (j = 0; j < NI; j++) {
11170                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
11171                if (DEBUG_SHOW_INFO) {
11172                    Log.v(TAG, "    IntentFilter:");
11173                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
11174                }
11175                removeFilter(intent);
11176            }
11177        }
11178
11179        @Override
11180        protected boolean allowFilterResult(
11181                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
11182            ProviderInfo filterPi = filter.provider.info;
11183            for (int i = dest.size() - 1; i >= 0; i--) {
11184                ProviderInfo destPi = dest.get(i).providerInfo;
11185                if (destPi.name == filterPi.name
11186                        && destPi.packageName == filterPi.packageName) {
11187                    return false;
11188                }
11189            }
11190            return true;
11191        }
11192
11193        @Override
11194        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
11195            return new PackageParser.ProviderIntentInfo[size];
11196        }
11197
11198        @Override
11199        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
11200            if (!sUserManager.exists(userId))
11201                return true;
11202            PackageParser.Package p = filter.provider.owner;
11203            if (p != null) {
11204                PackageSetting ps = (PackageSetting) p.mExtras;
11205                if (ps != null) {
11206                    // System apps are never considered stopped for purposes of
11207                    // filtering, because there may be no way for the user to
11208                    // actually re-launch them.
11209                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
11210                            && ps.getStopped(userId);
11211                }
11212            }
11213            return false;
11214        }
11215
11216        @Override
11217        protected boolean isPackageForFilter(String packageName,
11218                PackageParser.ProviderIntentInfo info) {
11219            return packageName.equals(info.provider.owner.packageName);
11220        }
11221
11222        @Override
11223        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
11224                int match, int userId) {
11225            if (!sUserManager.exists(userId))
11226                return null;
11227            final PackageParser.ProviderIntentInfo info = filter;
11228            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
11229                return null;
11230            }
11231            final PackageParser.Provider provider = info.provider;
11232            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
11233            if (ps == null) {
11234                return null;
11235            }
11236            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
11237                    ps.readUserState(userId), userId);
11238            if (pi == null) {
11239                return null;
11240            }
11241            final ResolveInfo res = new ResolveInfo();
11242            res.providerInfo = pi;
11243            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
11244                res.filter = filter;
11245            }
11246            res.priority = info.getPriority();
11247            res.preferredOrder = provider.owner.mPreferredOrder;
11248            res.match = match;
11249            res.isDefault = info.hasDefault;
11250            res.labelRes = info.labelRes;
11251            res.nonLocalizedLabel = info.nonLocalizedLabel;
11252            res.icon = info.icon;
11253            res.system = res.providerInfo.applicationInfo.isSystemApp();
11254            return res;
11255        }
11256
11257        @Override
11258        protected void sortResults(List<ResolveInfo> results) {
11259            Collections.sort(results, mResolvePrioritySorter);
11260        }
11261
11262        @Override
11263        protected void dumpFilter(PrintWriter out, String prefix,
11264                PackageParser.ProviderIntentInfo filter) {
11265            out.print(prefix);
11266            out.print(
11267                    Integer.toHexString(System.identityHashCode(filter.provider)));
11268            out.print(' ');
11269            filter.provider.printComponentShortName(out);
11270            out.print(" filter ");
11271            out.println(Integer.toHexString(System.identityHashCode(filter)));
11272        }
11273
11274        @Override
11275        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
11276            return filter.provider;
11277        }
11278
11279        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
11280            PackageParser.Provider provider = (PackageParser.Provider)label;
11281            out.print(prefix); out.print(
11282                    Integer.toHexString(System.identityHashCode(provider)));
11283                    out.print(' ');
11284                    provider.printComponentShortName(out);
11285            if (count > 1) {
11286                out.print(" ("); out.print(count); out.print(" filters)");
11287            }
11288            out.println();
11289        }
11290
11291        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
11292                = new ArrayMap<ComponentName, PackageParser.Provider>();
11293        private int mFlags;
11294    }
11295
11296    private static final class EphemeralIntentResolver
11297            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
11298        @Override
11299        protected EphemeralResolveIntentInfo[] newArray(int size) {
11300            return new EphemeralResolveIntentInfo[size];
11301        }
11302
11303        @Override
11304        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
11305            return true;
11306        }
11307
11308        @Override
11309        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
11310                int userId) {
11311            if (!sUserManager.exists(userId)) {
11312                return null;
11313            }
11314            return info.getEphemeralResolveInfo();
11315        }
11316    }
11317
11318    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
11319            new Comparator<ResolveInfo>() {
11320        public int compare(ResolveInfo r1, ResolveInfo r2) {
11321            int v1 = r1.priority;
11322            int v2 = r2.priority;
11323            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
11324            if (v1 != v2) {
11325                return (v1 > v2) ? -1 : 1;
11326            }
11327            v1 = r1.preferredOrder;
11328            v2 = r2.preferredOrder;
11329            if (v1 != v2) {
11330                return (v1 > v2) ? -1 : 1;
11331            }
11332            if (r1.isDefault != r2.isDefault) {
11333                return r1.isDefault ? -1 : 1;
11334            }
11335            v1 = r1.match;
11336            v2 = r2.match;
11337            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
11338            if (v1 != v2) {
11339                return (v1 > v2) ? -1 : 1;
11340            }
11341            if (r1.system != r2.system) {
11342                return r1.system ? -1 : 1;
11343            }
11344            if (r1.activityInfo != null) {
11345                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
11346            }
11347            if (r1.serviceInfo != null) {
11348                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
11349            }
11350            if (r1.providerInfo != null) {
11351                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
11352            }
11353            return 0;
11354        }
11355    };
11356
11357    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
11358            new Comparator<ProviderInfo>() {
11359        public int compare(ProviderInfo p1, ProviderInfo p2) {
11360            final int v1 = p1.initOrder;
11361            final int v2 = p2.initOrder;
11362            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
11363        }
11364    };
11365
11366    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
11367            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
11368            final int[] userIds) {
11369        mHandler.post(new Runnable() {
11370            @Override
11371            public void run() {
11372                try {
11373                    final IActivityManager am = ActivityManagerNative.getDefault();
11374                    if (am == null) return;
11375                    final int[] resolvedUserIds;
11376                    if (userIds == null) {
11377                        resolvedUserIds = am.getRunningUserIds();
11378                    } else {
11379                        resolvedUserIds = userIds;
11380                    }
11381                    for (int id : resolvedUserIds) {
11382                        final Intent intent = new Intent(action,
11383                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
11384                        if (extras != null) {
11385                            intent.putExtras(extras);
11386                        }
11387                        if (targetPkg != null) {
11388                            intent.setPackage(targetPkg);
11389                        }
11390                        // Modify the UID when posting to other users
11391                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
11392                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
11393                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
11394                            intent.putExtra(Intent.EXTRA_UID, uid);
11395                        }
11396                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
11397                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
11398                        if (DEBUG_BROADCASTS) {
11399                            RuntimeException here = new RuntimeException("here");
11400                            here.fillInStackTrace();
11401                            Slog.d(TAG, "Sending to user " + id + ": "
11402                                    + intent.toShortString(false, true, false, false)
11403                                    + " " + intent.getExtras(), here);
11404                        }
11405                        am.broadcastIntent(null, intent, null, finishedReceiver,
11406                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
11407                                null, finishedReceiver != null, false, id);
11408                    }
11409                } catch (RemoteException ex) {
11410                }
11411            }
11412        });
11413    }
11414
11415    /**
11416     * Check if the external storage media is available. This is true if there
11417     * is a mounted external storage medium or if the external storage is
11418     * emulated.
11419     */
11420    private boolean isExternalMediaAvailable() {
11421        return mMediaMounted || Environment.isExternalStorageEmulated();
11422    }
11423
11424    @Override
11425    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
11426        // writer
11427        synchronized (mPackages) {
11428            if (!isExternalMediaAvailable()) {
11429                // If the external storage is no longer mounted at this point,
11430                // the caller may not have been able to delete all of this
11431                // packages files and can not delete any more.  Bail.
11432                return null;
11433            }
11434            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
11435            if (lastPackage != null) {
11436                pkgs.remove(lastPackage);
11437            }
11438            if (pkgs.size() > 0) {
11439                return pkgs.get(0);
11440            }
11441        }
11442        return null;
11443    }
11444
11445    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
11446        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
11447                userId, andCode ? 1 : 0, packageName);
11448        if (mSystemReady) {
11449            msg.sendToTarget();
11450        } else {
11451            if (mPostSystemReadyMessages == null) {
11452                mPostSystemReadyMessages = new ArrayList<>();
11453            }
11454            mPostSystemReadyMessages.add(msg);
11455        }
11456    }
11457
11458    void startCleaningPackages() {
11459        // reader
11460        if (!isExternalMediaAvailable()) {
11461            return;
11462        }
11463        synchronized (mPackages) {
11464            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
11465                return;
11466            }
11467        }
11468        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
11469        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
11470        IActivityManager am = ActivityManagerNative.getDefault();
11471        if (am != null) {
11472            try {
11473                am.startService(null, intent, null, mContext.getOpPackageName(),
11474                        UserHandle.USER_SYSTEM);
11475            } catch (RemoteException e) {
11476            }
11477        }
11478    }
11479
11480    @Override
11481    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
11482            int installFlags, String installerPackageName, int userId) {
11483        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
11484
11485        final int callingUid = Binder.getCallingUid();
11486        enforceCrossUserPermission(callingUid, userId,
11487                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
11488
11489        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11490            try {
11491                if (observer != null) {
11492                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
11493                }
11494            } catch (RemoteException re) {
11495            }
11496            return;
11497        }
11498
11499        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
11500            installFlags |= PackageManager.INSTALL_FROM_ADB;
11501
11502        } else {
11503            // Caller holds INSTALL_PACKAGES permission, so we're less strict
11504            // about installerPackageName.
11505
11506            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
11507            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
11508        }
11509
11510        UserHandle user;
11511        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
11512            user = UserHandle.ALL;
11513        } else {
11514            user = new UserHandle(userId);
11515        }
11516
11517        // Only system components can circumvent runtime permissions when installing.
11518        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
11519                && mContext.checkCallingOrSelfPermission(Manifest.permission
11520                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
11521            throw new SecurityException("You need the "
11522                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
11523                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
11524        }
11525
11526        final File originFile = new File(originPath);
11527        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
11528
11529        final Message msg = mHandler.obtainMessage(INIT_COPY);
11530        final VerificationInfo verificationInfo = new VerificationInfo(
11531                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
11532        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
11533                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
11534                null /*packageAbiOverride*/, null /*grantedPermissions*/,
11535                null /*certificates*/);
11536        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
11537        msg.obj = params;
11538
11539        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
11540                System.identityHashCode(msg.obj));
11541        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11542                System.identityHashCode(msg.obj));
11543
11544        mHandler.sendMessage(msg);
11545    }
11546
11547    void installStage(String packageName, File stagedDir, String stagedCid,
11548            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
11549            String installerPackageName, int installerUid, UserHandle user,
11550            Certificate[][] certificates) {
11551        if (DEBUG_EPHEMERAL) {
11552            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11553                Slog.d(TAG, "Ephemeral install of " + packageName);
11554            }
11555        }
11556        final VerificationInfo verificationInfo = new VerificationInfo(
11557                sessionParams.originatingUri, sessionParams.referrerUri,
11558                sessionParams.originatingUid, installerUid);
11559
11560        final OriginInfo origin;
11561        if (stagedDir != null) {
11562            origin = OriginInfo.fromStagedFile(stagedDir);
11563        } else {
11564            origin = OriginInfo.fromStagedContainer(stagedCid);
11565        }
11566
11567        final Message msg = mHandler.obtainMessage(INIT_COPY);
11568        final InstallParams params = new InstallParams(origin, null, observer,
11569                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
11570                verificationInfo, user, sessionParams.abiOverride,
11571                sessionParams.grantedRuntimePermissions, certificates);
11572        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
11573        msg.obj = params;
11574
11575        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
11576                System.identityHashCode(msg.obj));
11577        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11578                System.identityHashCode(msg.obj));
11579
11580        mHandler.sendMessage(msg);
11581    }
11582
11583    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11584            int userId) {
11585        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11586        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11587    }
11588
11589    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11590            int appId, int userId) {
11591        Bundle extras = new Bundle(1);
11592        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11593
11594        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11595                packageName, extras, 0, null, null, new int[] {userId});
11596        try {
11597            IActivityManager am = ActivityManagerNative.getDefault();
11598            if (isSystem && am.isUserRunning(userId, 0)) {
11599                // The just-installed/enabled app is bundled on the system, so presumed
11600                // to be able to run automatically without needing an explicit launch.
11601                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11602                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11603                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11604                        .setPackage(packageName);
11605                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11606                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11607            }
11608        } catch (RemoteException e) {
11609            // shouldn't happen
11610            Slog.w(TAG, "Unable to bootstrap installed package", e);
11611        }
11612    }
11613
11614    @Override
11615    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11616            int userId) {
11617        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11618        PackageSetting pkgSetting;
11619        final int uid = Binder.getCallingUid();
11620        enforceCrossUserPermission(uid, userId,
11621                true /* requireFullPermission */, true /* checkShell */,
11622                "setApplicationHiddenSetting for user " + userId);
11623
11624        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11625            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11626            return false;
11627        }
11628
11629        long callingId = Binder.clearCallingIdentity();
11630        try {
11631            boolean sendAdded = false;
11632            boolean sendRemoved = false;
11633            // writer
11634            synchronized (mPackages) {
11635                pkgSetting = mSettings.mPackages.get(packageName);
11636                if (pkgSetting == null) {
11637                    return false;
11638                }
11639                if (pkgSetting.getHidden(userId) != hidden) {
11640                    pkgSetting.setHidden(hidden, userId);
11641                    mSettings.writePackageRestrictionsLPr(userId);
11642                    if (hidden) {
11643                        sendRemoved = true;
11644                    } else {
11645                        sendAdded = true;
11646                    }
11647                }
11648            }
11649            if (sendAdded) {
11650                sendPackageAddedForUser(packageName, pkgSetting, userId);
11651                return true;
11652            }
11653            if (sendRemoved) {
11654                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11655                        "hiding pkg");
11656                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11657                return true;
11658            }
11659        } finally {
11660            Binder.restoreCallingIdentity(callingId);
11661        }
11662        return false;
11663    }
11664
11665    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11666            int userId) {
11667        final PackageRemovedInfo info = new PackageRemovedInfo();
11668        info.removedPackage = packageName;
11669        info.removedUsers = new int[] {userId};
11670        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11671        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11672    }
11673
11674    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11675        if (pkgList.length > 0) {
11676            Bundle extras = new Bundle(1);
11677            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11678
11679            sendPackageBroadcast(
11680                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11681                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11682                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11683                    new int[] {userId});
11684        }
11685    }
11686
11687    /**
11688     * Returns true if application is not found or there was an error. Otherwise it returns
11689     * the hidden state of the package for the given user.
11690     */
11691    @Override
11692    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11693        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11694        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11695                true /* requireFullPermission */, false /* checkShell */,
11696                "getApplicationHidden for user " + userId);
11697        PackageSetting pkgSetting;
11698        long callingId = Binder.clearCallingIdentity();
11699        try {
11700            // writer
11701            synchronized (mPackages) {
11702                pkgSetting = mSettings.mPackages.get(packageName);
11703                if (pkgSetting == null) {
11704                    return true;
11705                }
11706                return pkgSetting.getHidden(userId);
11707            }
11708        } finally {
11709            Binder.restoreCallingIdentity(callingId);
11710        }
11711    }
11712
11713    /**
11714     * @hide
11715     */
11716    @Override
11717    public int installExistingPackageAsUser(String packageName, int userId) {
11718        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11719                null);
11720        PackageSetting pkgSetting;
11721        final int uid = Binder.getCallingUid();
11722        enforceCrossUserPermission(uid, userId,
11723                true /* requireFullPermission */, true /* checkShell */,
11724                "installExistingPackage for user " + userId);
11725        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11726            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11727        }
11728
11729        long callingId = Binder.clearCallingIdentity();
11730        try {
11731            boolean installed = false;
11732
11733            // writer
11734            synchronized (mPackages) {
11735                pkgSetting = mSettings.mPackages.get(packageName);
11736                if (pkgSetting == null) {
11737                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11738                }
11739                if (!pkgSetting.getInstalled(userId)) {
11740                    pkgSetting.setInstalled(true, userId);
11741                    pkgSetting.setHidden(false, userId);
11742                    mSettings.writePackageRestrictionsLPr(userId);
11743                    installed = true;
11744                }
11745            }
11746
11747            if (installed) {
11748                if (pkgSetting.pkg != null) {
11749                    synchronized (mInstallLock) {
11750                        // We don't need to freeze for a brand new install
11751                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
11752                    }
11753                }
11754                sendPackageAddedForUser(packageName, pkgSetting, userId);
11755            }
11756        } finally {
11757            Binder.restoreCallingIdentity(callingId);
11758        }
11759
11760        return PackageManager.INSTALL_SUCCEEDED;
11761    }
11762
11763    boolean isUserRestricted(int userId, String restrictionKey) {
11764        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11765        if (restrictions.getBoolean(restrictionKey, false)) {
11766            Log.w(TAG, "User is restricted: " + restrictionKey);
11767            return true;
11768        }
11769        return false;
11770    }
11771
11772    @Override
11773    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11774            int userId) {
11775        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11776        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11777                true /* requireFullPermission */, true /* checkShell */,
11778                "setPackagesSuspended for user " + userId);
11779
11780        if (ArrayUtils.isEmpty(packageNames)) {
11781            return packageNames;
11782        }
11783
11784        // List of package names for whom the suspended state has changed.
11785        List<String> changedPackages = new ArrayList<>(packageNames.length);
11786        // List of package names for whom the suspended state is not set as requested in this
11787        // method.
11788        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11789        long callingId = Binder.clearCallingIdentity();
11790        try {
11791            for (int i = 0; i < packageNames.length; i++) {
11792                String packageName = packageNames[i];
11793                boolean changed = false;
11794                final int appId;
11795                synchronized (mPackages) {
11796                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11797                    if (pkgSetting == null) {
11798                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11799                                + "\". Skipping suspending/un-suspending.");
11800                        unactionedPackages.add(packageName);
11801                        continue;
11802                    }
11803                    appId = pkgSetting.appId;
11804                    if (pkgSetting.getSuspended(userId) != suspended) {
11805                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11806                            unactionedPackages.add(packageName);
11807                            continue;
11808                        }
11809                        pkgSetting.setSuspended(suspended, userId);
11810                        mSettings.writePackageRestrictionsLPr(userId);
11811                        changed = true;
11812                        changedPackages.add(packageName);
11813                    }
11814                }
11815
11816                if (changed && suspended) {
11817                    killApplication(packageName, UserHandle.getUid(userId, appId),
11818                            "suspending package");
11819                }
11820            }
11821        } finally {
11822            Binder.restoreCallingIdentity(callingId);
11823        }
11824
11825        if (!changedPackages.isEmpty()) {
11826            sendPackagesSuspendedForUser(changedPackages.toArray(
11827                    new String[changedPackages.size()]), userId, suspended);
11828        }
11829
11830        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11831    }
11832
11833    @Override
11834    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11835        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11836                true /* requireFullPermission */, false /* checkShell */,
11837                "isPackageSuspendedForUser for user " + userId);
11838        synchronized (mPackages) {
11839            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11840            if (pkgSetting == null) {
11841                throw new IllegalArgumentException("Unknown target package: " + packageName);
11842            }
11843            return pkgSetting.getSuspended(userId);
11844        }
11845    }
11846
11847    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11848        if (isPackageDeviceAdmin(packageName, userId)) {
11849            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11850                    + "\": has an active device admin");
11851            return false;
11852        }
11853
11854        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11855        if (packageName.equals(activeLauncherPackageName)) {
11856            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11857                    + "\": contains the active launcher");
11858            return false;
11859        }
11860
11861        if (packageName.equals(mRequiredInstallerPackage)) {
11862            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11863                    + "\": required for package installation");
11864            return false;
11865        }
11866
11867        if (packageName.equals(mRequiredVerifierPackage)) {
11868            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11869                    + "\": required for package verification");
11870            return false;
11871        }
11872
11873        if (packageName.equals(getDefaultDialerPackageName(userId))) {
11874            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11875                    + "\": is the default dialer");
11876            return false;
11877        }
11878
11879        return true;
11880    }
11881
11882    private String getActiveLauncherPackageName(int userId) {
11883        Intent intent = new Intent(Intent.ACTION_MAIN);
11884        intent.addCategory(Intent.CATEGORY_HOME);
11885        ResolveInfo resolveInfo = resolveIntent(
11886                intent,
11887                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11888                PackageManager.MATCH_DEFAULT_ONLY,
11889                userId);
11890
11891        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11892    }
11893
11894    private String getDefaultDialerPackageName(int userId) {
11895        synchronized (mPackages) {
11896            return mSettings.getDefaultDialerPackageNameLPw(userId);
11897        }
11898    }
11899
11900    @Override
11901    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11902        mContext.enforceCallingOrSelfPermission(
11903                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11904                "Only package verification agents can verify applications");
11905
11906        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11907        final PackageVerificationResponse response = new PackageVerificationResponse(
11908                verificationCode, Binder.getCallingUid());
11909        msg.arg1 = id;
11910        msg.obj = response;
11911        mHandler.sendMessage(msg);
11912    }
11913
11914    @Override
11915    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11916            long millisecondsToDelay) {
11917        mContext.enforceCallingOrSelfPermission(
11918                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11919                "Only package verification agents can extend verification timeouts");
11920
11921        final PackageVerificationState state = mPendingVerification.get(id);
11922        final PackageVerificationResponse response = new PackageVerificationResponse(
11923                verificationCodeAtTimeout, Binder.getCallingUid());
11924
11925        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11926            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11927        }
11928        if (millisecondsToDelay < 0) {
11929            millisecondsToDelay = 0;
11930        }
11931        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11932                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11933            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11934        }
11935
11936        if ((state != null) && !state.timeoutExtended()) {
11937            state.extendTimeout();
11938
11939            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11940            msg.arg1 = id;
11941            msg.obj = response;
11942            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11943        }
11944    }
11945
11946    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11947            int verificationCode, UserHandle user) {
11948        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11949        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11950        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11951        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11952        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11953
11954        mContext.sendBroadcastAsUser(intent, user,
11955                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11956    }
11957
11958    private ComponentName matchComponentForVerifier(String packageName,
11959            List<ResolveInfo> receivers) {
11960        ActivityInfo targetReceiver = null;
11961
11962        final int NR = receivers.size();
11963        for (int i = 0; i < NR; i++) {
11964            final ResolveInfo info = receivers.get(i);
11965            if (info.activityInfo == null) {
11966                continue;
11967            }
11968
11969            if (packageName.equals(info.activityInfo.packageName)) {
11970                targetReceiver = info.activityInfo;
11971                break;
11972            }
11973        }
11974
11975        if (targetReceiver == null) {
11976            return null;
11977        }
11978
11979        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11980    }
11981
11982    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11983            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11984        if (pkgInfo.verifiers.length == 0) {
11985            return null;
11986        }
11987
11988        final int N = pkgInfo.verifiers.length;
11989        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11990        for (int i = 0; i < N; i++) {
11991            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11992
11993            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11994                    receivers);
11995            if (comp == null) {
11996                continue;
11997            }
11998
11999            final int verifierUid = getUidForVerifier(verifierInfo);
12000            if (verifierUid == -1) {
12001                continue;
12002            }
12003
12004            if (DEBUG_VERIFY) {
12005                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
12006                        + " with the correct signature");
12007            }
12008            sufficientVerifiers.add(comp);
12009            verificationState.addSufficientVerifier(verifierUid);
12010        }
12011
12012        return sufficientVerifiers;
12013    }
12014
12015    private int getUidForVerifier(VerifierInfo verifierInfo) {
12016        synchronized (mPackages) {
12017            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
12018            if (pkg == null) {
12019                return -1;
12020            } else if (pkg.mSignatures.length != 1) {
12021                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12022                        + " has more than one signature; ignoring");
12023                return -1;
12024            }
12025
12026            /*
12027             * If the public key of the package's signature does not match
12028             * our expected public key, then this is a different package and
12029             * we should skip.
12030             */
12031
12032            final byte[] expectedPublicKey;
12033            try {
12034                final Signature verifierSig = pkg.mSignatures[0];
12035                final PublicKey publicKey = verifierSig.getPublicKey();
12036                expectedPublicKey = publicKey.getEncoded();
12037            } catch (CertificateException e) {
12038                return -1;
12039            }
12040
12041            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
12042
12043            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
12044                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
12045                        + " does not have the expected public key; ignoring");
12046                return -1;
12047            }
12048
12049            return pkg.applicationInfo.uid;
12050        }
12051    }
12052
12053    @Override
12054    public void finishPackageInstall(int token, boolean didLaunch) {
12055        enforceSystemOrRoot("Only the system is allowed to finish installs");
12056
12057        if (DEBUG_INSTALL) {
12058            Slog.v(TAG, "BM finishing package install for " + token);
12059        }
12060        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12061
12062        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
12063        mHandler.sendMessage(msg);
12064    }
12065
12066    /**
12067     * Get the verification agent timeout.
12068     *
12069     * @return verification timeout in milliseconds
12070     */
12071    private long getVerificationTimeout() {
12072        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
12073                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
12074                DEFAULT_VERIFICATION_TIMEOUT);
12075    }
12076
12077    /**
12078     * Get the default verification agent response code.
12079     *
12080     * @return default verification response code
12081     */
12082    private int getDefaultVerificationResponse() {
12083        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12084                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
12085                DEFAULT_VERIFICATION_RESPONSE);
12086    }
12087
12088    /**
12089     * Check whether or not package verification has been enabled.
12090     *
12091     * @return true if verification should be performed
12092     */
12093    private boolean isVerificationEnabled(int userId, int installFlags) {
12094        if (!DEFAULT_VERIFY_ENABLE) {
12095            return false;
12096        }
12097        // Ephemeral apps don't get the full verification treatment
12098        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
12099            if (DEBUG_EPHEMERAL) {
12100                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
12101            }
12102            return false;
12103        }
12104
12105        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
12106
12107        // Check if installing from ADB
12108        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
12109            // Do not run verification in a test harness environment
12110            if (ActivityManager.isRunningInTestHarness()) {
12111                return false;
12112            }
12113            if (ensureVerifyAppsEnabled) {
12114                return true;
12115            }
12116            // Check if the developer does not want package verification for ADB installs
12117            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12118                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
12119                return false;
12120            }
12121        }
12122
12123        if (ensureVerifyAppsEnabled) {
12124            return true;
12125        }
12126
12127        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12128                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
12129    }
12130
12131    @Override
12132    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
12133            throws RemoteException {
12134        mContext.enforceCallingOrSelfPermission(
12135                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
12136                "Only intentfilter verification agents can verify applications");
12137
12138        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
12139        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
12140                Binder.getCallingUid(), verificationCode, failedDomains);
12141        msg.arg1 = id;
12142        msg.obj = response;
12143        mHandler.sendMessage(msg);
12144    }
12145
12146    @Override
12147    public int getIntentVerificationStatus(String packageName, int userId) {
12148        synchronized (mPackages) {
12149            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
12150        }
12151    }
12152
12153    @Override
12154    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
12155        mContext.enforceCallingOrSelfPermission(
12156                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12157
12158        boolean result = false;
12159        synchronized (mPackages) {
12160            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
12161        }
12162        if (result) {
12163            scheduleWritePackageRestrictionsLocked(userId);
12164        }
12165        return result;
12166    }
12167
12168    @Override
12169    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
12170            String packageName) {
12171        synchronized (mPackages) {
12172            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
12173        }
12174    }
12175
12176    @Override
12177    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
12178        if (TextUtils.isEmpty(packageName)) {
12179            return ParceledListSlice.emptyList();
12180        }
12181        synchronized (mPackages) {
12182            PackageParser.Package pkg = mPackages.get(packageName);
12183            if (pkg == null || pkg.activities == null) {
12184                return ParceledListSlice.emptyList();
12185            }
12186            final int count = pkg.activities.size();
12187            ArrayList<IntentFilter> result = new ArrayList<>();
12188            for (int n=0; n<count; n++) {
12189                PackageParser.Activity activity = pkg.activities.get(n);
12190                if (activity.intents != null && activity.intents.size() > 0) {
12191                    result.addAll(activity.intents);
12192                }
12193            }
12194            return new ParceledListSlice<>(result);
12195        }
12196    }
12197
12198    @Override
12199    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
12200        mContext.enforceCallingOrSelfPermission(
12201                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12202
12203        synchronized (mPackages) {
12204            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
12205            if (packageName != null) {
12206                result |= updateIntentVerificationStatus(packageName,
12207                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
12208                        userId);
12209                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
12210                        packageName, userId);
12211            }
12212            return result;
12213        }
12214    }
12215
12216    @Override
12217    public String getDefaultBrowserPackageName(int userId) {
12218        synchronized (mPackages) {
12219            return mSettings.getDefaultBrowserPackageNameLPw(userId);
12220        }
12221    }
12222
12223    /**
12224     * Get the "allow unknown sources" setting.
12225     *
12226     * @return the current "allow unknown sources" setting
12227     */
12228    private int getUnknownSourcesSettings() {
12229        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
12230                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
12231                -1);
12232    }
12233
12234    @Override
12235    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
12236        final int uid = Binder.getCallingUid();
12237        // writer
12238        synchronized (mPackages) {
12239            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
12240            if (targetPackageSetting == null) {
12241                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
12242            }
12243
12244            PackageSetting installerPackageSetting;
12245            if (installerPackageName != null) {
12246                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
12247                if (installerPackageSetting == null) {
12248                    throw new IllegalArgumentException("Unknown installer package: "
12249                            + installerPackageName);
12250                }
12251            } else {
12252                installerPackageSetting = null;
12253            }
12254
12255            Signature[] callerSignature;
12256            Object obj = mSettings.getUserIdLPr(uid);
12257            if (obj != null) {
12258                if (obj instanceof SharedUserSetting) {
12259                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
12260                } else if (obj instanceof PackageSetting) {
12261                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
12262                } else {
12263                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
12264                }
12265            } else {
12266                throw new SecurityException("Unknown calling UID: " + uid);
12267            }
12268
12269            // Verify: can't set installerPackageName to a package that is
12270            // not signed with the same cert as the caller.
12271            if (installerPackageSetting != null) {
12272                if (compareSignatures(callerSignature,
12273                        installerPackageSetting.signatures.mSignatures)
12274                        != PackageManager.SIGNATURE_MATCH) {
12275                    throw new SecurityException(
12276                            "Caller does not have same cert as new installer package "
12277                            + installerPackageName);
12278                }
12279            }
12280
12281            // Verify: if target already has an installer package, it must
12282            // be signed with the same cert as the caller.
12283            if (targetPackageSetting.installerPackageName != null) {
12284                PackageSetting setting = mSettings.mPackages.get(
12285                        targetPackageSetting.installerPackageName);
12286                // If the currently set package isn't valid, then it's always
12287                // okay to change it.
12288                if (setting != null) {
12289                    if (compareSignatures(callerSignature,
12290                            setting.signatures.mSignatures)
12291                            != PackageManager.SIGNATURE_MATCH) {
12292                        throw new SecurityException(
12293                                "Caller does not have same cert as old installer package "
12294                                + targetPackageSetting.installerPackageName);
12295                    }
12296                }
12297            }
12298
12299            // Okay!
12300            targetPackageSetting.installerPackageName = installerPackageName;
12301            if (installerPackageName != null) {
12302                mSettings.mInstallerPackages.add(installerPackageName);
12303            }
12304            scheduleWriteSettingsLocked();
12305        }
12306    }
12307
12308    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
12309        // Queue up an async operation since the package installation may take a little while.
12310        mHandler.post(new Runnable() {
12311            public void run() {
12312                mHandler.removeCallbacks(this);
12313                 // Result object to be returned
12314                PackageInstalledInfo res = new PackageInstalledInfo();
12315                res.setReturnCode(currentStatus);
12316                res.uid = -1;
12317                res.pkg = null;
12318                res.removedInfo = null;
12319                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12320                    args.doPreInstall(res.returnCode);
12321                    synchronized (mInstallLock) {
12322                        installPackageTracedLI(args, res);
12323                    }
12324                    args.doPostInstall(res.returnCode, res.uid);
12325                }
12326
12327                // A restore should be performed at this point if (a) the install
12328                // succeeded, (b) the operation is not an update, and (c) the new
12329                // package has not opted out of backup participation.
12330                final boolean update = res.removedInfo != null
12331                        && res.removedInfo.removedPackage != null;
12332                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
12333                boolean doRestore = !update
12334                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
12335
12336                // Set up the post-install work request bookkeeping.  This will be used
12337                // and cleaned up by the post-install event handling regardless of whether
12338                // there's a restore pass performed.  Token values are >= 1.
12339                int token;
12340                if (mNextInstallToken < 0) mNextInstallToken = 1;
12341                token = mNextInstallToken++;
12342
12343                PostInstallData data = new PostInstallData(args, res);
12344                mRunningInstalls.put(token, data);
12345                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
12346
12347                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
12348                    // Pass responsibility to the Backup Manager.  It will perform a
12349                    // restore if appropriate, then pass responsibility back to the
12350                    // Package Manager to run the post-install observer callbacks
12351                    // and broadcasts.
12352                    IBackupManager bm = IBackupManager.Stub.asInterface(
12353                            ServiceManager.getService(Context.BACKUP_SERVICE));
12354                    if (bm != null) {
12355                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
12356                                + " to BM for possible restore");
12357                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
12358                        try {
12359                            // TODO: http://b/22388012
12360                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12361                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
12362                            } else {
12363                                doRestore = false;
12364                            }
12365                        } catch (RemoteException e) {
12366                            // can't happen; the backup manager is local
12367                        } catch (Exception e) {
12368                            Slog.e(TAG, "Exception trying to enqueue restore", e);
12369                            doRestore = false;
12370                        }
12371                    } else {
12372                        Slog.e(TAG, "Backup Manager not found!");
12373                        doRestore = false;
12374                    }
12375                }
12376
12377                if (!doRestore) {
12378                    // No restore possible, or the Backup Manager was mysteriously not
12379                    // available -- just fire the post-install work request directly.
12380                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
12381
12382                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
12383
12384                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
12385                    mHandler.sendMessage(msg);
12386                }
12387            }
12388        });
12389    }
12390
12391    /**
12392     * Callback from PackageSettings whenever an app is first transitioned out of the
12393     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
12394     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
12395     * here whether the app is the target of an ongoing install, and only send the
12396     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
12397     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
12398     * handling.
12399     */
12400    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
12401        // Serialize this with the rest of the install-process message chain.  In the
12402        // restore-at-install case, this Runnable will necessarily run before the
12403        // POST_INSTALL message is processed, so the contents of mRunningInstalls
12404        // are coherent.  In the non-restore case, the app has already completed install
12405        // and been launched through some other means, so it is not in a problematic
12406        // state for observers to see the FIRST_LAUNCH signal.
12407        mHandler.post(new Runnable() {
12408            @Override
12409            public void run() {
12410                for (int i = 0; i < mRunningInstalls.size(); i++) {
12411                    final PostInstallData data = mRunningInstalls.valueAt(i);
12412                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
12413                        // right package; but is it for the right user?
12414                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
12415                            if (userId == data.res.newUsers[uIndex]) {
12416                                if (DEBUG_BACKUP) {
12417                                    Slog.i(TAG, "Package " + pkgName
12418                                            + " being restored so deferring FIRST_LAUNCH");
12419                                }
12420                                return;
12421                            }
12422                        }
12423                    }
12424                }
12425                // didn't find it, so not being restored
12426                if (DEBUG_BACKUP) {
12427                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
12428                }
12429                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
12430            }
12431        });
12432    }
12433
12434    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
12435        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
12436                installerPkg, null, userIds);
12437    }
12438
12439    private abstract class HandlerParams {
12440        private static final int MAX_RETRIES = 4;
12441
12442        /**
12443         * Number of times startCopy() has been attempted and had a non-fatal
12444         * error.
12445         */
12446        private int mRetries = 0;
12447
12448        /** User handle for the user requesting the information or installation. */
12449        private final UserHandle mUser;
12450        String traceMethod;
12451        int traceCookie;
12452
12453        HandlerParams(UserHandle user) {
12454            mUser = user;
12455        }
12456
12457        UserHandle getUser() {
12458            return mUser;
12459        }
12460
12461        HandlerParams setTraceMethod(String traceMethod) {
12462            this.traceMethod = traceMethod;
12463            return this;
12464        }
12465
12466        HandlerParams setTraceCookie(int traceCookie) {
12467            this.traceCookie = traceCookie;
12468            return this;
12469        }
12470
12471        final boolean startCopy() {
12472            boolean res;
12473            try {
12474                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
12475
12476                if (++mRetries > MAX_RETRIES) {
12477                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
12478                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
12479                    handleServiceError();
12480                    return false;
12481                } else {
12482                    handleStartCopy();
12483                    res = true;
12484                }
12485            } catch (RemoteException e) {
12486                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
12487                mHandler.sendEmptyMessage(MCS_RECONNECT);
12488                res = false;
12489            }
12490            handleReturnCode();
12491            return res;
12492        }
12493
12494        final void serviceError() {
12495            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
12496            handleServiceError();
12497            handleReturnCode();
12498        }
12499
12500        abstract void handleStartCopy() throws RemoteException;
12501        abstract void handleServiceError();
12502        abstract void handleReturnCode();
12503    }
12504
12505    class MeasureParams extends HandlerParams {
12506        private final PackageStats mStats;
12507        private boolean mSuccess;
12508
12509        private final IPackageStatsObserver mObserver;
12510
12511        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
12512            super(new UserHandle(stats.userHandle));
12513            mObserver = observer;
12514            mStats = stats;
12515        }
12516
12517        @Override
12518        public String toString() {
12519            return "MeasureParams{"
12520                + Integer.toHexString(System.identityHashCode(this))
12521                + " " + mStats.packageName + "}";
12522        }
12523
12524        @Override
12525        void handleStartCopy() throws RemoteException {
12526            synchronized (mInstallLock) {
12527                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
12528            }
12529
12530            if (mSuccess) {
12531                final boolean mounted;
12532                if (Environment.isExternalStorageEmulated()) {
12533                    mounted = true;
12534                } else {
12535                    final String status = Environment.getExternalStorageState();
12536                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
12537                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
12538                }
12539
12540                if (mounted) {
12541                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
12542
12543                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
12544                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
12545
12546                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
12547                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
12548
12549                    // Always subtract cache size, since it's a subdirectory
12550                    mStats.externalDataSize -= mStats.externalCacheSize;
12551
12552                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
12553                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
12554
12555                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
12556                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
12557                }
12558            }
12559        }
12560
12561        @Override
12562        void handleReturnCode() {
12563            if (mObserver != null) {
12564                try {
12565                    mObserver.onGetStatsCompleted(mStats, mSuccess);
12566                } catch (RemoteException e) {
12567                    Slog.i(TAG, "Observer no longer exists.");
12568                }
12569            }
12570        }
12571
12572        @Override
12573        void handleServiceError() {
12574            Slog.e(TAG, "Could not measure application " + mStats.packageName
12575                            + " external storage");
12576        }
12577    }
12578
12579    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
12580            throws RemoteException {
12581        long result = 0;
12582        for (File path : paths) {
12583            result += mcs.calculateDirectorySize(path.getAbsolutePath());
12584        }
12585        return result;
12586    }
12587
12588    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
12589        for (File path : paths) {
12590            try {
12591                mcs.clearDirectory(path.getAbsolutePath());
12592            } catch (RemoteException e) {
12593            }
12594        }
12595    }
12596
12597    static class OriginInfo {
12598        /**
12599         * Location where install is coming from, before it has been
12600         * copied/renamed into place. This could be a single monolithic APK
12601         * file, or a cluster directory. This location may be untrusted.
12602         */
12603        final File file;
12604        final String cid;
12605
12606        /**
12607         * Flag indicating that {@link #file} or {@link #cid} has already been
12608         * staged, meaning downstream users don't need to defensively copy the
12609         * contents.
12610         */
12611        final boolean staged;
12612
12613        /**
12614         * Flag indicating that {@link #file} or {@link #cid} is an already
12615         * installed app that is being moved.
12616         */
12617        final boolean existing;
12618
12619        final String resolvedPath;
12620        final File resolvedFile;
12621
12622        static OriginInfo fromNothing() {
12623            return new OriginInfo(null, null, false, false);
12624        }
12625
12626        static OriginInfo fromUntrustedFile(File file) {
12627            return new OriginInfo(file, null, false, false);
12628        }
12629
12630        static OriginInfo fromExistingFile(File file) {
12631            return new OriginInfo(file, null, false, true);
12632        }
12633
12634        static OriginInfo fromStagedFile(File file) {
12635            return new OriginInfo(file, null, true, false);
12636        }
12637
12638        static OriginInfo fromStagedContainer(String cid) {
12639            return new OriginInfo(null, cid, true, false);
12640        }
12641
12642        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12643            this.file = file;
12644            this.cid = cid;
12645            this.staged = staged;
12646            this.existing = existing;
12647
12648            if (cid != null) {
12649                resolvedPath = PackageHelper.getSdDir(cid);
12650                resolvedFile = new File(resolvedPath);
12651            } else if (file != null) {
12652                resolvedPath = file.getAbsolutePath();
12653                resolvedFile = file;
12654            } else {
12655                resolvedPath = null;
12656                resolvedFile = null;
12657            }
12658        }
12659    }
12660
12661    static class MoveInfo {
12662        final int moveId;
12663        final String fromUuid;
12664        final String toUuid;
12665        final String packageName;
12666        final String dataAppName;
12667        final int appId;
12668        final String seinfo;
12669        final int targetSdkVersion;
12670
12671        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12672                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12673            this.moveId = moveId;
12674            this.fromUuid = fromUuid;
12675            this.toUuid = toUuid;
12676            this.packageName = packageName;
12677            this.dataAppName = dataAppName;
12678            this.appId = appId;
12679            this.seinfo = seinfo;
12680            this.targetSdkVersion = targetSdkVersion;
12681        }
12682    }
12683
12684    static class VerificationInfo {
12685        /** A constant used to indicate that a uid value is not present. */
12686        public static final int NO_UID = -1;
12687
12688        /** URI referencing where the package was downloaded from. */
12689        final Uri originatingUri;
12690
12691        /** HTTP referrer URI associated with the originatingURI. */
12692        final Uri referrer;
12693
12694        /** UID of the application that the install request originated from. */
12695        final int originatingUid;
12696
12697        /** UID of application requesting the install */
12698        final int installerUid;
12699
12700        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12701            this.originatingUri = originatingUri;
12702            this.referrer = referrer;
12703            this.originatingUid = originatingUid;
12704            this.installerUid = installerUid;
12705        }
12706    }
12707
12708    class InstallParams extends HandlerParams {
12709        final OriginInfo origin;
12710        final MoveInfo move;
12711        final IPackageInstallObserver2 observer;
12712        int installFlags;
12713        final String installerPackageName;
12714        final String volumeUuid;
12715        private InstallArgs mArgs;
12716        private int mRet;
12717        final String packageAbiOverride;
12718        final String[] grantedRuntimePermissions;
12719        final VerificationInfo verificationInfo;
12720        final Certificate[][] certificates;
12721
12722        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12723                int installFlags, String installerPackageName, String volumeUuid,
12724                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12725                String[] grantedPermissions, Certificate[][] certificates) {
12726            super(user);
12727            this.origin = origin;
12728            this.move = move;
12729            this.observer = observer;
12730            this.installFlags = installFlags;
12731            this.installerPackageName = installerPackageName;
12732            this.volumeUuid = volumeUuid;
12733            this.verificationInfo = verificationInfo;
12734            this.packageAbiOverride = packageAbiOverride;
12735            this.grantedRuntimePermissions = grantedPermissions;
12736            this.certificates = certificates;
12737        }
12738
12739        @Override
12740        public String toString() {
12741            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12742                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12743        }
12744
12745        private int installLocationPolicy(PackageInfoLite pkgLite) {
12746            String packageName = pkgLite.packageName;
12747            int installLocation = pkgLite.installLocation;
12748            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12749            // reader
12750            synchronized (mPackages) {
12751                // Currently installed package which the new package is attempting to replace or
12752                // null if no such package is installed.
12753                PackageParser.Package installedPkg = mPackages.get(packageName);
12754                // Package which currently owns the data which the new package will own if installed.
12755                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12756                // will be null whereas dataOwnerPkg will contain information about the package
12757                // which was uninstalled while keeping its data.
12758                PackageParser.Package dataOwnerPkg = installedPkg;
12759                if (dataOwnerPkg  == null) {
12760                    PackageSetting ps = mSettings.mPackages.get(packageName);
12761                    if (ps != null) {
12762                        dataOwnerPkg = ps.pkg;
12763                    }
12764                }
12765
12766                if (dataOwnerPkg != null) {
12767                    // If installed, the package will get access to data left on the device by its
12768                    // predecessor. As a security measure, this is permited only if this is not a
12769                    // version downgrade or if the predecessor package is marked as debuggable and
12770                    // a downgrade is explicitly requested.
12771                    //
12772                    // On debuggable platform builds, downgrades are permitted even for
12773                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12774                    // not offer security guarantees and thus it's OK to disable some security
12775                    // mechanisms to make debugging/testing easier on those builds. However, even on
12776                    // debuggable builds downgrades of packages are permitted only if requested via
12777                    // installFlags. This is because we aim to keep the behavior of debuggable
12778                    // platform builds as close as possible to the behavior of non-debuggable
12779                    // platform builds.
12780                    final boolean downgradeRequested =
12781                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12782                    final boolean packageDebuggable =
12783                                (dataOwnerPkg.applicationInfo.flags
12784                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12785                    final boolean downgradePermitted =
12786                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12787                    if (!downgradePermitted) {
12788                        try {
12789                            checkDowngrade(dataOwnerPkg, pkgLite);
12790                        } catch (PackageManagerException e) {
12791                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12792                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12793                        }
12794                    }
12795                }
12796
12797                if (installedPkg != null) {
12798                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12799                        // Check for updated system application.
12800                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12801                            if (onSd) {
12802                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12803                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12804                            }
12805                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12806                        } else {
12807                            if (onSd) {
12808                                // Install flag overrides everything.
12809                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12810                            }
12811                            // If current upgrade specifies particular preference
12812                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12813                                // Application explicitly specified internal.
12814                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12815                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12816                                // App explictly prefers external. Let policy decide
12817                            } else {
12818                                // Prefer previous location
12819                                if (isExternal(installedPkg)) {
12820                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12821                                }
12822                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12823                            }
12824                        }
12825                    } else {
12826                        // Invalid install. Return error code
12827                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12828                    }
12829                }
12830            }
12831            // All the special cases have been taken care of.
12832            // Return result based on recommended install location.
12833            if (onSd) {
12834                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12835            }
12836            return pkgLite.recommendedInstallLocation;
12837        }
12838
12839        /*
12840         * Invoke remote method to get package information and install
12841         * location values. Override install location based on default
12842         * policy if needed and then create install arguments based
12843         * on the install location.
12844         */
12845        public void handleStartCopy() throws RemoteException {
12846            int ret = PackageManager.INSTALL_SUCCEEDED;
12847
12848            // If we're already staged, we've firmly committed to an install location
12849            if (origin.staged) {
12850                if (origin.file != null) {
12851                    installFlags |= PackageManager.INSTALL_INTERNAL;
12852                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12853                } else if (origin.cid != null) {
12854                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12855                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12856                } else {
12857                    throw new IllegalStateException("Invalid stage location");
12858                }
12859            }
12860
12861            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12862            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12863            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12864            PackageInfoLite pkgLite = null;
12865
12866            if (onInt && onSd) {
12867                // Check if both bits are set.
12868                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12869                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12870            } else if (onSd && ephemeral) {
12871                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12872                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12873            } else {
12874                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12875                        packageAbiOverride);
12876
12877                if (DEBUG_EPHEMERAL && ephemeral) {
12878                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12879                }
12880
12881                /*
12882                 * If we have too little free space, try to free cache
12883                 * before giving up.
12884                 */
12885                if (!origin.staged && pkgLite.recommendedInstallLocation
12886                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12887                    // TODO: focus freeing disk space on the target device
12888                    final StorageManager storage = StorageManager.from(mContext);
12889                    final long lowThreshold = storage.getStorageLowBytes(
12890                            Environment.getDataDirectory());
12891
12892                    final long sizeBytes = mContainerService.calculateInstalledSize(
12893                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12894
12895                    try {
12896                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12897                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12898                                installFlags, packageAbiOverride);
12899                    } catch (InstallerException e) {
12900                        Slog.w(TAG, "Failed to free cache", e);
12901                    }
12902
12903                    /*
12904                     * The cache free must have deleted the file we
12905                     * downloaded to install.
12906                     *
12907                     * TODO: fix the "freeCache" call to not delete
12908                     *       the file we care about.
12909                     */
12910                    if (pkgLite.recommendedInstallLocation
12911                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12912                        pkgLite.recommendedInstallLocation
12913                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12914                    }
12915                }
12916            }
12917
12918            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12919                int loc = pkgLite.recommendedInstallLocation;
12920                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12921                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12922                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12923                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12924                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12925                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12926                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12927                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12928                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12929                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12930                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12931                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12932                } else {
12933                    // Override with defaults if needed.
12934                    loc = installLocationPolicy(pkgLite);
12935                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12936                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12937                    } else if (!onSd && !onInt) {
12938                        // Override install location with flags
12939                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12940                            // Set the flag to install on external media.
12941                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12942                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12943                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12944                            if (DEBUG_EPHEMERAL) {
12945                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12946                            }
12947                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12948                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12949                                    |PackageManager.INSTALL_INTERNAL);
12950                        } else {
12951                            // Make sure the flag for installing on external
12952                            // media is unset
12953                            installFlags |= PackageManager.INSTALL_INTERNAL;
12954                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12955                        }
12956                    }
12957                }
12958            }
12959
12960            final InstallArgs args = createInstallArgs(this);
12961            mArgs = args;
12962
12963            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12964                // TODO: http://b/22976637
12965                // Apps installed for "all" users use the device owner to verify the app
12966                UserHandle verifierUser = getUser();
12967                if (verifierUser == UserHandle.ALL) {
12968                    verifierUser = UserHandle.SYSTEM;
12969                }
12970
12971                /*
12972                 * Determine if we have any installed package verifiers. If we
12973                 * do, then we'll defer to them to verify the packages.
12974                 */
12975                final int requiredUid = mRequiredVerifierPackage == null ? -1
12976                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12977                                verifierUser.getIdentifier());
12978                if (!origin.existing && requiredUid != -1
12979                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12980                    final Intent verification = new Intent(
12981                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12982                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12983                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12984                            PACKAGE_MIME_TYPE);
12985                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12986
12987                    // Query all live verifiers based on current user state
12988                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12989                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12990
12991                    if (DEBUG_VERIFY) {
12992                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12993                                + verification.toString() + " with " + pkgLite.verifiers.length
12994                                + " optional verifiers");
12995                    }
12996
12997                    final int verificationId = mPendingVerificationToken++;
12998
12999                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
13000
13001                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
13002                            installerPackageName);
13003
13004                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
13005                            installFlags);
13006
13007                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
13008                            pkgLite.packageName);
13009
13010                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
13011                            pkgLite.versionCode);
13012
13013                    if (verificationInfo != null) {
13014                        if (verificationInfo.originatingUri != null) {
13015                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
13016                                    verificationInfo.originatingUri);
13017                        }
13018                        if (verificationInfo.referrer != null) {
13019                            verification.putExtra(Intent.EXTRA_REFERRER,
13020                                    verificationInfo.referrer);
13021                        }
13022                        if (verificationInfo.originatingUid >= 0) {
13023                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
13024                                    verificationInfo.originatingUid);
13025                        }
13026                        if (verificationInfo.installerUid >= 0) {
13027                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
13028                                    verificationInfo.installerUid);
13029                        }
13030                    }
13031
13032                    final PackageVerificationState verificationState = new PackageVerificationState(
13033                            requiredUid, args);
13034
13035                    mPendingVerification.append(verificationId, verificationState);
13036
13037                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
13038                            receivers, verificationState);
13039
13040                    /*
13041                     * If any sufficient verifiers were listed in the package
13042                     * manifest, attempt to ask them.
13043                     */
13044                    if (sufficientVerifiers != null) {
13045                        final int N = sufficientVerifiers.size();
13046                        if (N == 0) {
13047                            Slog.i(TAG, "Additional verifiers required, but none installed.");
13048                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
13049                        } else {
13050                            for (int i = 0; i < N; i++) {
13051                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
13052
13053                                final Intent sufficientIntent = new Intent(verification);
13054                                sufficientIntent.setComponent(verifierComponent);
13055                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
13056                            }
13057                        }
13058                    }
13059
13060                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
13061                            mRequiredVerifierPackage, receivers);
13062                    if (ret == PackageManager.INSTALL_SUCCEEDED
13063                            && mRequiredVerifierPackage != null) {
13064                        Trace.asyncTraceBegin(
13065                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
13066                        /*
13067                         * Send the intent to the required verification agent,
13068                         * but only start the verification timeout after the
13069                         * target BroadcastReceivers have run.
13070                         */
13071                        verification.setComponent(requiredVerifierComponent);
13072                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
13073                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13074                                new BroadcastReceiver() {
13075                                    @Override
13076                                    public void onReceive(Context context, Intent intent) {
13077                                        final Message msg = mHandler
13078                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
13079                                        msg.arg1 = verificationId;
13080                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
13081                                    }
13082                                }, null, 0, null, null);
13083
13084                        /*
13085                         * We don't want the copy to proceed until verification
13086                         * succeeds, so null out this field.
13087                         */
13088                        mArgs = null;
13089                    }
13090                } else {
13091                    /*
13092                     * No package verification is enabled, so immediately start
13093                     * the remote call to initiate copy using temporary file.
13094                     */
13095                    ret = args.copyApk(mContainerService, true);
13096                }
13097            }
13098
13099            mRet = ret;
13100        }
13101
13102        @Override
13103        void handleReturnCode() {
13104            // If mArgs is null, then MCS couldn't be reached. When it
13105            // reconnects, it will try again to install. At that point, this
13106            // will succeed.
13107            if (mArgs != null) {
13108                processPendingInstall(mArgs, mRet);
13109            }
13110        }
13111
13112        @Override
13113        void handleServiceError() {
13114            mArgs = createInstallArgs(this);
13115            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13116        }
13117
13118        public boolean isForwardLocked() {
13119            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13120        }
13121    }
13122
13123    /**
13124     * Used during creation of InstallArgs
13125     *
13126     * @param installFlags package installation flags
13127     * @return true if should be installed on external storage
13128     */
13129    private static boolean installOnExternalAsec(int installFlags) {
13130        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
13131            return false;
13132        }
13133        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
13134            return true;
13135        }
13136        return false;
13137    }
13138
13139    /**
13140     * Used during creation of InstallArgs
13141     *
13142     * @param installFlags package installation flags
13143     * @return true if should be installed as forward locked
13144     */
13145    private static boolean installForwardLocked(int installFlags) {
13146        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13147    }
13148
13149    private InstallArgs createInstallArgs(InstallParams params) {
13150        if (params.move != null) {
13151            return new MoveInstallArgs(params);
13152        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
13153            return new AsecInstallArgs(params);
13154        } else {
13155            return new FileInstallArgs(params);
13156        }
13157    }
13158
13159    /**
13160     * Create args that describe an existing installed package. Typically used
13161     * when cleaning up old installs, or used as a move source.
13162     */
13163    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
13164            String resourcePath, String[] instructionSets) {
13165        final boolean isInAsec;
13166        if (installOnExternalAsec(installFlags)) {
13167            /* Apps on SD card are always in ASEC containers. */
13168            isInAsec = true;
13169        } else if (installForwardLocked(installFlags)
13170                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
13171            /*
13172             * Forward-locked apps are only in ASEC containers if they're the
13173             * new style
13174             */
13175            isInAsec = true;
13176        } else {
13177            isInAsec = false;
13178        }
13179
13180        if (isInAsec) {
13181            return new AsecInstallArgs(codePath, instructionSets,
13182                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
13183        } else {
13184            return new FileInstallArgs(codePath, resourcePath, instructionSets);
13185        }
13186    }
13187
13188    static abstract class InstallArgs {
13189        /** @see InstallParams#origin */
13190        final OriginInfo origin;
13191        /** @see InstallParams#move */
13192        final MoveInfo move;
13193
13194        final IPackageInstallObserver2 observer;
13195        // Always refers to PackageManager flags only
13196        final int installFlags;
13197        final String installerPackageName;
13198        final String volumeUuid;
13199        final UserHandle user;
13200        final String abiOverride;
13201        final String[] installGrantPermissions;
13202        /** If non-null, drop an async trace when the install completes */
13203        final String traceMethod;
13204        final int traceCookie;
13205        final Certificate[][] certificates;
13206
13207        // The list of instruction sets supported by this app. This is currently
13208        // only used during the rmdex() phase to clean up resources. We can get rid of this
13209        // if we move dex files under the common app path.
13210        /* nullable */ String[] instructionSets;
13211
13212        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
13213                int installFlags, String installerPackageName, String volumeUuid,
13214                UserHandle user, String[] instructionSets,
13215                String abiOverride, String[] installGrantPermissions,
13216                String traceMethod, int traceCookie, Certificate[][] certificates) {
13217            this.origin = origin;
13218            this.move = move;
13219            this.installFlags = installFlags;
13220            this.observer = observer;
13221            this.installerPackageName = installerPackageName;
13222            this.volumeUuid = volumeUuid;
13223            this.user = user;
13224            this.instructionSets = instructionSets;
13225            this.abiOverride = abiOverride;
13226            this.installGrantPermissions = installGrantPermissions;
13227            this.traceMethod = traceMethod;
13228            this.traceCookie = traceCookie;
13229            this.certificates = certificates;
13230        }
13231
13232        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
13233        abstract int doPreInstall(int status);
13234
13235        /**
13236         * Rename package into final resting place. All paths on the given
13237         * scanned package should be updated to reflect the rename.
13238         */
13239        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
13240        abstract int doPostInstall(int status, int uid);
13241
13242        /** @see PackageSettingBase#codePathString */
13243        abstract String getCodePath();
13244        /** @see PackageSettingBase#resourcePathString */
13245        abstract String getResourcePath();
13246
13247        // Need installer lock especially for dex file removal.
13248        abstract void cleanUpResourcesLI();
13249        abstract boolean doPostDeleteLI(boolean delete);
13250
13251        /**
13252         * Called before the source arguments are copied. This is used mostly
13253         * for MoveParams when it needs to read the source file to put it in the
13254         * destination.
13255         */
13256        int doPreCopy() {
13257            return PackageManager.INSTALL_SUCCEEDED;
13258        }
13259
13260        /**
13261         * Called after the source arguments are copied. This is used mostly for
13262         * MoveParams when it needs to read the source file to put it in the
13263         * destination.
13264         */
13265        int doPostCopy(int uid) {
13266            return PackageManager.INSTALL_SUCCEEDED;
13267        }
13268
13269        protected boolean isFwdLocked() {
13270            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
13271        }
13272
13273        protected boolean isExternalAsec() {
13274            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
13275        }
13276
13277        protected boolean isEphemeral() {
13278            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13279        }
13280
13281        UserHandle getUser() {
13282            return user;
13283        }
13284    }
13285
13286    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
13287        if (!allCodePaths.isEmpty()) {
13288            if (instructionSets == null) {
13289                throw new IllegalStateException("instructionSet == null");
13290            }
13291            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
13292            for (String codePath : allCodePaths) {
13293                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
13294                    try {
13295                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
13296                    } catch (InstallerException ignored) {
13297                    }
13298                }
13299            }
13300        }
13301    }
13302
13303    /**
13304     * Logic to handle installation of non-ASEC applications, including copying
13305     * and renaming logic.
13306     */
13307    class FileInstallArgs extends InstallArgs {
13308        private File codeFile;
13309        private File resourceFile;
13310
13311        // Example topology:
13312        // /data/app/com.example/base.apk
13313        // /data/app/com.example/split_foo.apk
13314        // /data/app/com.example/lib/arm/libfoo.so
13315        // /data/app/com.example/lib/arm64/libfoo.so
13316        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
13317
13318        /** New install */
13319        FileInstallArgs(InstallParams params) {
13320            super(params.origin, params.move, params.observer, params.installFlags,
13321                    params.installerPackageName, params.volumeUuid,
13322                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
13323                    params.grantedRuntimePermissions,
13324                    params.traceMethod, params.traceCookie, params.certificates);
13325            if (isFwdLocked()) {
13326                throw new IllegalArgumentException("Forward locking only supported in ASEC");
13327            }
13328        }
13329
13330        /** Existing install */
13331        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
13332            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
13333                    null, null, null, 0, null /*certificates*/);
13334            this.codeFile = (codePath != null) ? new File(codePath) : null;
13335            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
13336        }
13337
13338        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13339            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
13340            try {
13341                return doCopyApk(imcs, temp);
13342            } finally {
13343                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13344            }
13345        }
13346
13347        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13348            if (origin.staged) {
13349                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
13350                codeFile = origin.file;
13351                resourceFile = origin.file;
13352                return PackageManager.INSTALL_SUCCEEDED;
13353            }
13354
13355            try {
13356                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
13357                final File tempDir =
13358                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
13359                codeFile = tempDir;
13360                resourceFile = tempDir;
13361            } catch (IOException e) {
13362                Slog.w(TAG, "Failed to create copy file: " + e);
13363                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
13364            }
13365
13366            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
13367                @Override
13368                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
13369                    if (!FileUtils.isValidExtFilename(name)) {
13370                        throw new IllegalArgumentException("Invalid filename: " + name);
13371                    }
13372                    try {
13373                        final File file = new File(codeFile, name);
13374                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
13375                                O_RDWR | O_CREAT, 0644);
13376                        Os.chmod(file.getAbsolutePath(), 0644);
13377                        return new ParcelFileDescriptor(fd);
13378                    } catch (ErrnoException e) {
13379                        throw new RemoteException("Failed to open: " + e.getMessage());
13380                    }
13381                }
13382            };
13383
13384            int ret = PackageManager.INSTALL_SUCCEEDED;
13385            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
13386            if (ret != PackageManager.INSTALL_SUCCEEDED) {
13387                Slog.e(TAG, "Failed to copy package");
13388                return ret;
13389            }
13390
13391            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
13392            NativeLibraryHelper.Handle handle = null;
13393            try {
13394                handle = NativeLibraryHelper.Handle.create(codeFile);
13395                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
13396                        abiOverride);
13397            } catch (IOException e) {
13398                Slog.e(TAG, "Copying native libraries failed", e);
13399                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13400            } finally {
13401                IoUtils.closeQuietly(handle);
13402            }
13403
13404            return ret;
13405        }
13406
13407        int doPreInstall(int status) {
13408            if (status != PackageManager.INSTALL_SUCCEEDED) {
13409                cleanUp();
13410            }
13411            return status;
13412        }
13413
13414        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13415            if (status != PackageManager.INSTALL_SUCCEEDED) {
13416                cleanUp();
13417                return false;
13418            }
13419
13420            final File targetDir = codeFile.getParentFile();
13421            final File beforeCodeFile = codeFile;
13422            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
13423
13424            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
13425            try {
13426                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
13427            } catch (ErrnoException e) {
13428                Slog.w(TAG, "Failed to rename", e);
13429                return false;
13430            }
13431
13432            if (!SELinux.restoreconRecursive(afterCodeFile)) {
13433                Slog.w(TAG, "Failed to restorecon");
13434                return false;
13435            }
13436
13437            // Reflect the rename internally
13438            codeFile = afterCodeFile;
13439            resourceFile = afterCodeFile;
13440
13441            // Reflect the rename in scanned details
13442            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13443            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13444                    afterCodeFile, pkg.baseCodePath));
13445            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13446                    afterCodeFile, pkg.splitCodePaths));
13447
13448            // Reflect the rename in app info
13449            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13450            pkg.setApplicationInfoCodePath(pkg.codePath);
13451            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13452            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13453            pkg.setApplicationInfoResourcePath(pkg.codePath);
13454            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13455            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13456
13457            return true;
13458        }
13459
13460        int doPostInstall(int status, int uid) {
13461            if (status != PackageManager.INSTALL_SUCCEEDED) {
13462                cleanUp();
13463            }
13464            return status;
13465        }
13466
13467        @Override
13468        String getCodePath() {
13469            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13470        }
13471
13472        @Override
13473        String getResourcePath() {
13474            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13475        }
13476
13477        private boolean cleanUp() {
13478            if (codeFile == null || !codeFile.exists()) {
13479                return false;
13480            }
13481
13482            removeCodePathLI(codeFile);
13483
13484            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
13485                resourceFile.delete();
13486            }
13487
13488            return true;
13489        }
13490
13491        void cleanUpResourcesLI() {
13492            // Try enumerating all code paths before deleting
13493            List<String> allCodePaths = Collections.EMPTY_LIST;
13494            if (codeFile != null && codeFile.exists()) {
13495                try {
13496                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13497                    allCodePaths = pkg.getAllCodePaths();
13498                } catch (PackageParserException e) {
13499                    // Ignored; we tried our best
13500                }
13501            }
13502
13503            cleanUp();
13504            removeDexFiles(allCodePaths, instructionSets);
13505        }
13506
13507        boolean doPostDeleteLI(boolean delete) {
13508            // XXX err, shouldn't we respect the delete flag?
13509            cleanUpResourcesLI();
13510            return true;
13511        }
13512    }
13513
13514    private boolean isAsecExternal(String cid) {
13515        final String asecPath = PackageHelper.getSdFilesystem(cid);
13516        return !asecPath.startsWith(mAsecInternalPath);
13517    }
13518
13519    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
13520            PackageManagerException {
13521        if (copyRet < 0) {
13522            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
13523                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
13524                throw new PackageManagerException(copyRet, message);
13525            }
13526        }
13527    }
13528
13529    /**
13530     * Extract the MountService "container ID" from the full code path of an
13531     * .apk.
13532     */
13533    static String cidFromCodePath(String fullCodePath) {
13534        int eidx = fullCodePath.lastIndexOf("/");
13535        String subStr1 = fullCodePath.substring(0, eidx);
13536        int sidx = subStr1.lastIndexOf("/");
13537        return subStr1.substring(sidx+1, eidx);
13538    }
13539
13540    /**
13541     * Logic to handle installation of ASEC applications, including copying and
13542     * renaming logic.
13543     */
13544    class AsecInstallArgs extends InstallArgs {
13545        static final String RES_FILE_NAME = "pkg.apk";
13546        static final String PUBLIC_RES_FILE_NAME = "res.zip";
13547
13548        String cid;
13549        String packagePath;
13550        String resourcePath;
13551
13552        /** New install */
13553        AsecInstallArgs(InstallParams params) {
13554            super(params.origin, params.move, params.observer, params.installFlags,
13555                    params.installerPackageName, params.volumeUuid,
13556                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13557                    params.grantedRuntimePermissions,
13558                    params.traceMethod, params.traceCookie, params.certificates);
13559        }
13560
13561        /** Existing install */
13562        AsecInstallArgs(String fullCodePath, String[] instructionSets,
13563                        boolean isExternal, boolean isForwardLocked) {
13564            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
13565              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13566                    instructionSets, null, null, null, 0, null /*certificates*/);
13567            // Hackily pretend we're still looking at a full code path
13568            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
13569                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
13570            }
13571
13572            // Extract cid from fullCodePath
13573            int eidx = fullCodePath.lastIndexOf("/");
13574            String subStr1 = fullCodePath.substring(0, eidx);
13575            int sidx = subStr1.lastIndexOf("/");
13576            cid = subStr1.substring(sidx+1, eidx);
13577            setMountPath(subStr1);
13578        }
13579
13580        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
13581            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
13582              | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
13583                    instructionSets, null, null, null, 0, null /*certificates*/);
13584            this.cid = cid;
13585            setMountPath(PackageHelper.getSdDir(cid));
13586        }
13587
13588        void createCopyFile() {
13589            cid = mInstallerService.allocateExternalStageCidLegacy();
13590        }
13591
13592        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
13593            if (origin.staged && origin.cid != null) {
13594                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
13595                cid = origin.cid;
13596                setMountPath(PackageHelper.getSdDir(cid));
13597                return PackageManager.INSTALL_SUCCEEDED;
13598            }
13599
13600            if (temp) {
13601                createCopyFile();
13602            } else {
13603                /*
13604                 * Pre-emptively destroy the container since it's destroyed if
13605                 * copying fails due to it existing anyway.
13606                 */
13607                PackageHelper.destroySdDir(cid);
13608            }
13609
13610            final String newMountPath = imcs.copyPackageToContainer(
13611                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
13612                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
13613
13614            if (newMountPath != null) {
13615                setMountPath(newMountPath);
13616                return PackageManager.INSTALL_SUCCEEDED;
13617            } else {
13618                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13619            }
13620        }
13621
13622        @Override
13623        String getCodePath() {
13624            return packagePath;
13625        }
13626
13627        @Override
13628        String getResourcePath() {
13629            return resourcePath;
13630        }
13631
13632        int doPreInstall(int status) {
13633            if (status != PackageManager.INSTALL_SUCCEEDED) {
13634                // Destroy container
13635                PackageHelper.destroySdDir(cid);
13636            } else {
13637                boolean mounted = PackageHelper.isContainerMounted(cid);
13638                if (!mounted) {
13639                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13640                            Process.SYSTEM_UID);
13641                    if (newMountPath != null) {
13642                        setMountPath(newMountPath);
13643                    } else {
13644                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13645                    }
13646                }
13647            }
13648            return status;
13649        }
13650
13651        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13652            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13653            String newMountPath = null;
13654            if (PackageHelper.isContainerMounted(cid)) {
13655                // Unmount the container
13656                if (!PackageHelper.unMountSdDir(cid)) {
13657                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13658                    return false;
13659                }
13660            }
13661            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13662                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13663                        " which might be stale. Will try to clean up.");
13664                // Clean up the stale container and proceed to recreate.
13665                if (!PackageHelper.destroySdDir(newCacheId)) {
13666                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13667                    return false;
13668                }
13669                // Successfully cleaned up stale container. Try to rename again.
13670                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13671                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13672                            + " inspite of cleaning it up.");
13673                    return false;
13674                }
13675            }
13676            if (!PackageHelper.isContainerMounted(newCacheId)) {
13677                Slog.w(TAG, "Mounting container " + newCacheId);
13678                newMountPath = PackageHelper.mountSdDir(newCacheId,
13679                        getEncryptKey(), Process.SYSTEM_UID);
13680            } else {
13681                newMountPath = PackageHelper.getSdDir(newCacheId);
13682            }
13683            if (newMountPath == null) {
13684                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13685                return false;
13686            }
13687            Log.i(TAG, "Succesfully renamed " + cid +
13688                    " to " + newCacheId +
13689                    " at new path: " + newMountPath);
13690            cid = newCacheId;
13691
13692            final File beforeCodeFile = new File(packagePath);
13693            setMountPath(newMountPath);
13694            final File afterCodeFile = new File(packagePath);
13695
13696            // Reflect the rename in scanned details
13697            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13698            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13699                    afterCodeFile, pkg.baseCodePath));
13700            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13701                    afterCodeFile, pkg.splitCodePaths));
13702
13703            // Reflect the rename in app info
13704            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13705            pkg.setApplicationInfoCodePath(pkg.codePath);
13706            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13707            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13708            pkg.setApplicationInfoResourcePath(pkg.codePath);
13709            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13710            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13711
13712            return true;
13713        }
13714
13715        private void setMountPath(String mountPath) {
13716            final File mountFile = new File(mountPath);
13717
13718            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13719            if (monolithicFile.exists()) {
13720                packagePath = monolithicFile.getAbsolutePath();
13721                if (isFwdLocked()) {
13722                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13723                } else {
13724                    resourcePath = packagePath;
13725                }
13726            } else {
13727                packagePath = mountFile.getAbsolutePath();
13728                resourcePath = packagePath;
13729            }
13730        }
13731
13732        int doPostInstall(int status, int uid) {
13733            if (status != PackageManager.INSTALL_SUCCEEDED) {
13734                cleanUp();
13735            } else {
13736                final int groupOwner;
13737                final String protectedFile;
13738                if (isFwdLocked()) {
13739                    groupOwner = UserHandle.getSharedAppGid(uid);
13740                    protectedFile = RES_FILE_NAME;
13741                } else {
13742                    groupOwner = -1;
13743                    protectedFile = null;
13744                }
13745
13746                if (uid < Process.FIRST_APPLICATION_UID
13747                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13748                    Slog.e(TAG, "Failed to finalize " + cid);
13749                    PackageHelper.destroySdDir(cid);
13750                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13751                }
13752
13753                boolean mounted = PackageHelper.isContainerMounted(cid);
13754                if (!mounted) {
13755                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13756                }
13757            }
13758            return status;
13759        }
13760
13761        private void cleanUp() {
13762            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13763
13764            // Destroy secure container
13765            PackageHelper.destroySdDir(cid);
13766        }
13767
13768        private List<String> getAllCodePaths() {
13769            final File codeFile = new File(getCodePath());
13770            if (codeFile != null && codeFile.exists()) {
13771                try {
13772                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13773                    return pkg.getAllCodePaths();
13774                } catch (PackageParserException e) {
13775                    // Ignored; we tried our best
13776                }
13777            }
13778            return Collections.EMPTY_LIST;
13779        }
13780
13781        void cleanUpResourcesLI() {
13782            // Enumerate all code paths before deleting
13783            cleanUpResourcesLI(getAllCodePaths());
13784        }
13785
13786        private void cleanUpResourcesLI(List<String> allCodePaths) {
13787            cleanUp();
13788            removeDexFiles(allCodePaths, instructionSets);
13789        }
13790
13791        String getPackageName() {
13792            return getAsecPackageName(cid);
13793        }
13794
13795        boolean doPostDeleteLI(boolean delete) {
13796            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13797            final List<String> allCodePaths = getAllCodePaths();
13798            boolean mounted = PackageHelper.isContainerMounted(cid);
13799            if (mounted) {
13800                // Unmount first
13801                if (PackageHelper.unMountSdDir(cid)) {
13802                    mounted = false;
13803                }
13804            }
13805            if (!mounted && delete) {
13806                cleanUpResourcesLI(allCodePaths);
13807            }
13808            return !mounted;
13809        }
13810
13811        @Override
13812        int doPreCopy() {
13813            if (isFwdLocked()) {
13814                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13815                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13816                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13817                }
13818            }
13819
13820            return PackageManager.INSTALL_SUCCEEDED;
13821        }
13822
13823        @Override
13824        int doPostCopy(int uid) {
13825            if (isFwdLocked()) {
13826                if (uid < Process.FIRST_APPLICATION_UID
13827                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13828                                RES_FILE_NAME)) {
13829                    Slog.e(TAG, "Failed to finalize " + cid);
13830                    PackageHelper.destroySdDir(cid);
13831                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13832                }
13833            }
13834
13835            return PackageManager.INSTALL_SUCCEEDED;
13836        }
13837    }
13838
13839    /**
13840     * Logic to handle movement of existing installed applications.
13841     */
13842    class MoveInstallArgs extends InstallArgs {
13843        private File codeFile;
13844        private File resourceFile;
13845
13846        /** New install */
13847        MoveInstallArgs(InstallParams params) {
13848            super(params.origin, params.move, params.observer, params.installFlags,
13849                    params.installerPackageName, params.volumeUuid,
13850                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13851                    params.grantedRuntimePermissions,
13852                    params.traceMethod, params.traceCookie, params.certificates);
13853        }
13854
13855        int copyApk(IMediaContainerService imcs, boolean temp) {
13856            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13857                    + move.fromUuid + " to " + move.toUuid);
13858            synchronized (mInstaller) {
13859                try {
13860                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13861                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13862                } catch (InstallerException e) {
13863                    Slog.w(TAG, "Failed to move app", e);
13864                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13865                }
13866            }
13867
13868            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13869            resourceFile = codeFile;
13870            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13871
13872            return PackageManager.INSTALL_SUCCEEDED;
13873        }
13874
13875        int doPreInstall(int status) {
13876            if (status != PackageManager.INSTALL_SUCCEEDED) {
13877                cleanUp(move.toUuid);
13878            }
13879            return status;
13880        }
13881
13882        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13883            if (status != PackageManager.INSTALL_SUCCEEDED) {
13884                cleanUp(move.toUuid);
13885                return false;
13886            }
13887
13888            // Reflect the move in app info
13889            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13890            pkg.setApplicationInfoCodePath(pkg.codePath);
13891            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13892            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13893            pkg.setApplicationInfoResourcePath(pkg.codePath);
13894            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13895            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13896
13897            return true;
13898        }
13899
13900        int doPostInstall(int status, int uid) {
13901            if (status == PackageManager.INSTALL_SUCCEEDED) {
13902                cleanUp(move.fromUuid);
13903            } else {
13904                cleanUp(move.toUuid);
13905            }
13906            return status;
13907        }
13908
13909        @Override
13910        String getCodePath() {
13911            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13912        }
13913
13914        @Override
13915        String getResourcePath() {
13916            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13917        }
13918
13919        private boolean cleanUp(String volumeUuid) {
13920            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13921                    move.dataAppName);
13922            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13923            final int[] userIds = sUserManager.getUserIds();
13924            synchronized (mInstallLock) {
13925                // Clean up both app data and code
13926                // All package moves are frozen until finished
13927                for (int userId : userIds) {
13928                    try {
13929                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
13930                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
13931                    } catch (InstallerException e) {
13932                        Slog.w(TAG, String.valueOf(e));
13933                    }
13934                }
13935                removeCodePathLI(codeFile);
13936            }
13937            return true;
13938        }
13939
13940        void cleanUpResourcesLI() {
13941            throw new UnsupportedOperationException();
13942        }
13943
13944        boolean doPostDeleteLI(boolean delete) {
13945            throw new UnsupportedOperationException();
13946        }
13947    }
13948
13949    static String getAsecPackageName(String packageCid) {
13950        int idx = packageCid.lastIndexOf("-");
13951        if (idx == -1) {
13952            return packageCid;
13953        }
13954        return packageCid.substring(0, idx);
13955    }
13956
13957    // Utility method used to create code paths based on package name and available index.
13958    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13959        String idxStr = "";
13960        int idx = 1;
13961        // Fall back to default value of idx=1 if prefix is not
13962        // part of oldCodePath
13963        if (oldCodePath != null) {
13964            String subStr = oldCodePath;
13965            // Drop the suffix right away
13966            if (suffix != null && subStr.endsWith(suffix)) {
13967                subStr = subStr.substring(0, subStr.length() - suffix.length());
13968            }
13969            // If oldCodePath already contains prefix find out the
13970            // ending index to either increment or decrement.
13971            int sidx = subStr.lastIndexOf(prefix);
13972            if (sidx != -1) {
13973                subStr = subStr.substring(sidx + prefix.length());
13974                if (subStr != null) {
13975                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13976                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13977                    }
13978                    try {
13979                        idx = Integer.parseInt(subStr);
13980                        if (idx <= 1) {
13981                            idx++;
13982                        } else {
13983                            idx--;
13984                        }
13985                    } catch(NumberFormatException e) {
13986                    }
13987                }
13988            }
13989        }
13990        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13991        return prefix + idxStr;
13992    }
13993
13994    private File getNextCodePath(File targetDir, String packageName) {
13995        int suffix = 1;
13996        File result;
13997        do {
13998            result = new File(targetDir, packageName + "-" + suffix);
13999            suffix++;
14000        } while (result.exists());
14001        return result;
14002    }
14003
14004    // Utility method that returns the relative package path with respect
14005    // to the installation directory. Like say for /data/data/com.test-1.apk
14006    // string com.test-1 is returned.
14007    static String deriveCodePathName(String codePath) {
14008        if (codePath == null) {
14009            return null;
14010        }
14011        final File codeFile = new File(codePath);
14012        final String name = codeFile.getName();
14013        if (codeFile.isDirectory()) {
14014            return name;
14015        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
14016            final int lastDot = name.lastIndexOf('.');
14017            return name.substring(0, lastDot);
14018        } else {
14019            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
14020            return null;
14021        }
14022    }
14023
14024    static class PackageInstalledInfo {
14025        String name;
14026        int uid;
14027        // The set of users that originally had this package installed.
14028        int[] origUsers;
14029        // The set of users that now have this package installed.
14030        int[] newUsers;
14031        PackageParser.Package pkg;
14032        int returnCode;
14033        String returnMsg;
14034        PackageRemovedInfo removedInfo;
14035        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
14036
14037        public void setError(int code, String msg) {
14038            setReturnCode(code);
14039            setReturnMessage(msg);
14040            Slog.w(TAG, msg);
14041        }
14042
14043        public void setError(String msg, PackageParserException e) {
14044            setReturnCode(e.error);
14045            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14046            Slog.w(TAG, msg, e);
14047        }
14048
14049        public void setError(String msg, PackageManagerException e) {
14050            returnCode = e.error;
14051            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
14052            Slog.w(TAG, msg, e);
14053        }
14054
14055        public void setReturnCode(int returnCode) {
14056            this.returnCode = returnCode;
14057            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14058            for (int i = 0; i < childCount; i++) {
14059                addedChildPackages.valueAt(i).returnCode = returnCode;
14060            }
14061        }
14062
14063        private void setReturnMessage(String returnMsg) {
14064            this.returnMsg = returnMsg;
14065            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
14066            for (int i = 0; i < childCount; i++) {
14067                addedChildPackages.valueAt(i).returnMsg = returnMsg;
14068            }
14069        }
14070
14071        // In some error cases we want to convey more info back to the observer
14072        String origPackage;
14073        String origPermission;
14074    }
14075
14076    /*
14077     * Install a non-existing package.
14078     */
14079    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
14080            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
14081            PackageInstalledInfo res) {
14082        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
14083
14084        // Remember this for later, in case we need to rollback this install
14085        String pkgName = pkg.packageName;
14086
14087        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
14088
14089        synchronized(mPackages) {
14090            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
14091                // A package with the same name is already installed, though
14092                // it has been renamed to an older name.  The package we
14093                // are trying to install should be installed as an update to
14094                // the existing one, but that has not been requested, so bail.
14095                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14096                        + " without first uninstalling package running as "
14097                        + mSettings.mRenamedPackages.get(pkgName));
14098                return;
14099            }
14100            if (mPackages.containsKey(pkgName)) {
14101                // Don't allow installation over an existing package with the same name.
14102                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
14103                        + " without first uninstalling.");
14104                return;
14105            }
14106        }
14107
14108        try {
14109            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
14110                    System.currentTimeMillis(), user);
14111
14112            updateSettingsLI(newPackage, installerPackageName, null, res, user);
14113
14114            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14115                prepareAppDataAfterInstallLIF(newPackage);
14116
14117            } else {
14118                // Remove package from internal structures, but keep around any
14119                // data that might have already existed
14120                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
14121                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
14122            }
14123        } catch (PackageManagerException e) {
14124            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14125        }
14126
14127        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14128    }
14129
14130    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
14131        // Can't rotate keys during boot or if sharedUser.
14132        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
14133                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
14134            return false;
14135        }
14136        // app is using upgradeKeySets; make sure all are valid
14137        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14138        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
14139        for (int i = 0; i < upgradeKeySets.length; i++) {
14140            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
14141                Slog.wtf(TAG, "Package "
14142                         + (oldPs.name != null ? oldPs.name : "<null>")
14143                         + " contains upgrade-key-set reference to unknown key-set: "
14144                         + upgradeKeySets[i]
14145                         + " reverting to signatures check.");
14146                return false;
14147            }
14148        }
14149        return true;
14150    }
14151
14152    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
14153        // Upgrade keysets are being used.  Determine if new package has a superset of the
14154        // required keys.
14155        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
14156        KeySetManagerService ksms = mSettings.mKeySetManagerService;
14157        for (int i = 0; i < upgradeKeySets.length; i++) {
14158            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
14159            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
14160                return true;
14161            }
14162        }
14163        return false;
14164    }
14165
14166    private static void updateDigest(MessageDigest digest, File file) throws IOException {
14167        try (DigestInputStream digestStream =
14168                new DigestInputStream(new FileInputStream(file), digest)) {
14169            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
14170        }
14171    }
14172
14173    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
14174            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
14175        final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
14176
14177        final PackageParser.Package oldPackage;
14178        final String pkgName = pkg.packageName;
14179        final int[] allUsers;
14180        final int[] installedUsers;
14181
14182        synchronized(mPackages) {
14183            oldPackage = mPackages.get(pkgName);
14184            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
14185
14186            // don't allow upgrade to target a release SDK from a pre-release SDK
14187            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
14188                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14189            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
14190                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
14191            if (oldTargetsPreRelease
14192                    && !newTargetsPreRelease
14193                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
14194                Slog.w(TAG, "Can't install package targeting released sdk");
14195                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
14196                return;
14197            }
14198
14199            // don't allow an upgrade from full to ephemeral
14200            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
14201            if (isEphemeral && !oldIsEphemeral) {
14202                // can't downgrade from full to ephemeral
14203                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
14204                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14205                return;
14206            }
14207
14208            // verify signatures are valid
14209            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14210            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14211                if (!checkUpgradeKeySetLP(ps, pkg)) {
14212                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14213                            "New package not signed by keys specified by upgrade-keysets: "
14214                                    + pkgName);
14215                    return;
14216                }
14217            } else {
14218                // default to original signature matching
14219                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
14220                        != PackageManager.SIGNATURE_MATCH) {
14221                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
14222                            "New package has a different signature: " + pkgName);
14223                    return;
14224                }
14225            }
14226
14227            // don't allow a system upgrade unless the upgrade hash matches
14228            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
14229                byte[] digestBytes = null;
14230                try {
14231                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
14232                    updateDigest(digest, new File(pkg.baseCodePath));
14233                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
14234                        for (String path : pkg.splitCodePaths) {
14235                            updateDigest(digest, new File(path));
14236                        }
14237                    }
14238                    digestBytes = digest.digest();
14239                } catch (NoSuchAlgorithmException | IOException e) {
14240                    res.setError(INSTALL_FAILED_INVALID_APK,
14241                            "Could not compute hash: " + pkgName);
14242                    return;
14243                }
14244                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
14245                    res.setError(INSTALL_FAILED_INVALID_APK,
14246                            "New package fails restrict-update check: " + pkgName);
14247                    return;
14248                }
14249                // retain upgrade restriction
14250                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
14251            }
14252
14253            // Check for shared user id changes
14254            String invalidPackageName =
14255                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
14256            if (invalidPackageName != null) {
14257                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
14258                        "Package " + invalidPackageName + " tried to change user "
14259                                + oldPackage.mSharedUserId);
14260                return;
14261            }
14262
14263            // In case of rollback, remember per-user/profile install state
14264            allUsers = sUserManager.getUserIds();
14265            installedUsers = ps.queryInstalledUsers(allUsers, true);
14266        }
14267
14268        // Update what is removed
14269        res.removedInfo = new PackageRemovedInfo();
14270        res.removedInfo.uid = oldPackage.applicationInfo.uid;
14271        res.removedInfo.removedPackage = oldPackage.packageName;
14272        res.removedInfo.isUpdate = true;
14273        res.removedInfo.origUsers = installedUsers;
14274        final int childCount = (oldPackage.childPackages != null)
14275                ? oldPackage.childPackages.size() : 0;
14276        for (int i = 0; i < childCount; i++) {
14277            boolean childPackageUpdated = false;
14278            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
14279            if (res.addedChildPackages != null) {
14280                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14281                if (childRes != null) {
14282                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
14283                    childRes.removedInfo.removedPackage = childPkg.packageName;
14284                    childRes.removedInfo.isUpdate = true;
14285                    childPackageUpdated = true;
14286                }
14287            }
14288            if (!childPackageUpdated) {
14289                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
14290                childRemovedRes.removedPackage = childPkg.packageName;
14291                childRemovedRes.isUpdate = false;
14292                childRemovedRes.dataRemoved = true;
14293                synchronized (mPackages) {
14294                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14295                    if (childPs != null) {
14296                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
14297                    }
14298                }
14299                if (res.removedInfo.removedChildPackages == null) {
14300                    res.removedInfo.removedChildPackages = new ArrayMap<>();
14301                }
14302                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
14303            }
14304        }
14305
14306        boolean sysPkg = (isSystemApp(oldPackage));
14307        if (sysPkg) {
14308            // Set the system/privileged flags as needed
14309            final boolean privileged =
14310                    (oldPackage.applicationInfo.privateFlags
14311                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14312            final int systemPolicyFlags = policyFlags
14313                    | PackageParser.PARSE_IS_SYSTEM
14314                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
14315
14316            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
14317                    user, allUsers, installerPackageName, res);
14318        } else {
14319            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
14320                    user, allUsers, installerPackageName, res);
14321        }
14322    }
14323
14324    public List<String> getPreviousCodePaths(String packageName) {
14325        final PackageSetting ps = mSettings.mPackages.get(packageName);
14326        final List<String> result = new ArrayList<String>();
14327        if (ps != null && ps.oldCodePaths != null) {
14328            result.addAll(ps.oldCodePaths);
14329        }
14330        return result;
14331    }
14332
14333    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
14334            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14335            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14336        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
14337                + deletedPackage);
14338
14339        String pkgName = deletedPackage.packageName;
14340        boolean deletedPkg = true;
14341        boolean addedPkg = false;
14342        boolean updatedSettings = false;
14343        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
14344        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
14345                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
14346
14347        final long origUpdateTime = (pkg.mExtras != null)
14348                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
14349
14350        // First delete the existing package while retaining the data directory
14351        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14352                res.removedInfo, true, pkg)) {
14353            // If the existing package wasn't successfully deleted
14354            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
14355            deletedPkg = false;
14356        } else {
14357            // Successfully deleted the old package; proceed with replace.
14358
14359            // If deleted package lived in a container, give users a chance to
14360            // relinquish resources before killing.
14361            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
14362                if (DEBUG_INSTALL) {
14363                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
14364                }
14365                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
14366                final ArrayList<String> pkgList = new ArrayList<String>(1);
14367                pkgList.add(deletedPackage.applicationInfo.packageName);
14368                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
14369            }
14370
14371            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14372                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14373            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14374
14375            try {
14376                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
14377                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
14378                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14379
14380                // Update the in-memory copy of the previous code paths.
14381                PackageSetting ps = mSettings.mPackages.get(pkgName);
14382                if (!killApp) {
14383                    if (ps.oldCodePaths == null) {
14384                        ps.oldCodePaths = new ArraySet<>();
14385                    }
14386                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
14387                    if (deletedPackage.splitCodePaths != null) {
14388                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
14389                    }
14390                } else {
14391                    ps.oldCodePaths = null;
14392                }
14393                if (ps.childPackageNames != null) {
14394                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
14395                        final String childPkgName = ps.childPackageNames.get(i);
14396                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
14397                        childPs.oldCodePaths = ps.oldCodePaths;
14398                    }
14399                }
14400                prepareAppDataAfterInstallLIF(newPackage);
14401                addedPkg = true;
14402            } catch (PackageManagerException e) {
14403                res.setError("Package couldn't be installed in " + pkg.codePath, e);
14404            }
14405        }
14406
14407        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14408            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
14409
14410            // Revert all internal state mutations and added folders for the failed install
14411            if (addedPkg) {
14412                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
14413                        res.removedInfo, true, null);
14414            }
14415
14416            // Restore the old package
14417            if (deletedPkg) {
14418                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
14419                File restoreFile = new File(deletedPackage.codePath);
14420                // Parse old package
14421                boolean oldExternal = isExternal(deletedPackage);
14422                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
14423                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
14424                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
14425                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
14426                try {
14427                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
14428                            null);
14429                } catch (PackageManagerException e) {
14430                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
14431                            + e.getMessage());
14432                    return;
14433                }
14434
14435                synchronized (mPackages) {
14436                    // Ensure the installer package name up to date
14437                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14438
14439                    // Update permissions for restored package
14440                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14441
14442                    mSettings.writeLPr();
14443                }
14444
14445                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
14446            }
14447        } else {
14448            synchronized (mPackages) {
14449                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
14450                if (ps != null) {
14451                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
14452                    if (res.removedInfo.removedChildPackages != null) {
14453                        final int childCount = res.removedInfo.removedChildPackages.size();
14454                        // Iterate in reverse as we may modify the collection
14455                        for (int i = childCount - 1; i >= 0; i--) {
14456                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
14457                            if (res.addedChildPackages.containsKey(childPackageName)) {
14458                                res.removedInfo.removedChildPackages.removeAt(i);
14459                            } else {
14460                                PackageRemovedInfo childInfo = res.removedInfo
14461                                        .removedChildPackages.valueAt(i);
14462                                childInfo.removedForAllUsers = mPackages.get(
14463                                        childInfo.removedPackage) == null;
14464                            }
14465                        }
14466                    }
14467                }
14468            }
14469        }
14470    }
14471
14472    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
14473            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
14474            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
14475        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
14476                + ", old=" + deletedPackage);
14477
14478        final boolean disabledSystem;
14479
14480        // Remove existing system package
14481        removePackageLI(deletedPackage, true);
14482
14483        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
14484        if (!disabledSystem) {
14485            // We didn't need to disable the .apk as a current system package,
14486            // which means we are replacing another update that is already
14487            // installed.  We need to make sure to delete the older one's .apk.
14488            res.removedInfo.args = createInstallArgsForExisting(0,
14489                    deletedPackage.applicationInfo.getCodePath(),
14490                    deletedPackage.applicationInfo.getResourcePath(),
14491                    getAppDexInstructionSets(deletedPackage.applicationInfo));
14492        } else {
14493            res.removedInfo.args = null;
14494        }
14495
14496        // Successfully disabled the old package. Now proceed with re-installation
14497        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
14498                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
14499        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
14500
14501        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14502        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
14503                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
14504
14505        PackageParser.Package newPackage = null;
14506        try {
14507            // Add the package to the internal data structures
14508            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
14509
14510            // Set the update and install times
14511            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
14512            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
14513                    System.currentTimeMillis());
14514
14515            // Update the package dynamic state if succeeded
14516            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14517                // Now that the install succeeded make sure we remove data
14518                // directories for any child package the update removed.
14519                final int deletedChildCount = (deletedPackage.childPackages != null)
14520                        ? deletedPackage.childPackages.size() : 0;
14521                final int newChildCount = (newPackage.childPackages != null)
14522                        ? newPackage.childPackages.size() : 0;
14523                for (int i = 0; i < deletedChildCount; i++) {
14524                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
14525                    boolean childPackageDeleted = true;
14526                    for (int j = 0; j < newChildCount; j++) {
14527                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
14528                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
14529                            childPackageDeleted = false;
14530                            break;
14531                        }
14532                    }
14533                    if (childPackageDeleted) {
14534                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
14535                                deletedChildPkg.packageName);
14536                        if (ps != null && res.removedInfo.removedChildPackages != null) {
14537                            PackageRemovedInfo removedChildRes = res.removedInfo
14538                                    .removedChildPackages.get(deletedChildPkg.packageName);
14539                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
14540                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
14541                        }
14542                    }
14543                }
14544
14545                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
14546                prepareAppDataAfterInstallLIF(newPackage);
14547            }
14548        } catch (PackageManagerException e) {
14549            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
14550            res.setError("Package couldn't be installed in " + pkg.codePath, e);
14551        }
14552
14553        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14554            // Re installation failed. Restore old information
14555            // Remove new pkg information
14556            if (newPackage != null) {
14557                removeInstalledPackageLI(newPackage, true);
14558            }
14559            // Add back the old system package
14560            try {
14561                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
14562            } catch (PackageManagerException e) {
14563                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
14564            }
14565
14566            synchronized (mPackages) {
14567                if (disabledSystem) {
14568                    enableSystemPackageLPw(deletedPackage);
14569                }
14570
14571                // Ensure the installer package name up to date
14572                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
14573
14574                // Update permissions for restored package
14575                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
14576
14577                mSettings.writeLPr();
14578            }
14579
14580            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
14581                    + " after failed upgrade");
14582        }
14583    }
14584
14585    /**
14586     * Checks whether the parent or any of the child packages have a change shared
14587     * user. For a package to be a valid update the shred users of the parent and
14588     * the children should match. We may later support changing child shared users.
14589     * @param oldPkg The updated package.
14590     * @param newPkg The update package.
14591     * @return The shared user that change between the versions.
14592     */
14593    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
14594            PackageParser.Package newPkg) {
14595        // Check parent shared user
14596        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
14597            return newPkg.packageName;
14598        }
14599        // Check child shared users
14600        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14601        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
14602        for (int i = 0; i < newChildCount; i++) {
14603            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
14604            // If this child was present, did it have the same shared user?
14605            for (int j = 0; j < oldChildCount; j++) {
14606                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
14607                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
14608                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
14609                    return newChildPkg.packageName;
14610                }
14611            }
14612        }
14613        return null;
14614    }
14615
14616    private void removeNativeBinariesLI(PackageSetting ps) {
14617        // Remove the lib path for the parent package
14618        if (ps != null) {
14619            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
14620            // Remove the lib path for the child packages
14621            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14622            for (int i = 0; i < childCount; i++) {
14623                PackageSetting childPs = null;
14624                synchronized (mPackages) {
14625                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14626                }
14627                if (childPs != null) {
14628                    NativeLibraryHelper.removeNativeBinariesLI(childPs
14629                            .legacyNativeLibraryPathString);
14630                }
14631            }
14632        }
14633    }
14634
14635    private void enableSystemPackageLPw(PackageParser.Package pkg) {
14636        // Enable the parent package
14637        mSettings.enableSystemPackageLPw(pkg.packageName);
14638        // Enable the child packages
14639        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14640        for (int i = 0; i < childCount; i++) {
14641            PackageParser.Package childPkg = pkg.childPackages.get(i);
14642            mSettings.enableSystemPackageLPw(childPkg.packageName);
14643        }
14644    }
14645
14646    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
14647            PackageParser.Package newPkg) {
14648        // Disable the parent package (parent always replaced)
14649        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
14650        // Disable the child packages
14651        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
14652        for (int i = 0; i < childCount; i++) {
14653            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
14654            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
14655            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
14656        }
14657        return disabled;
14658    }
14659
14660    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
14661            String installerPackageName) {
14662        // Enable the parent package
14663        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
14664        // Enable the child packages
14665        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14666        for (int i = 0; i < childCount; i++) {
14667            PackageParser.Package childPkg = pkg.childPackages.get(i);
14668            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
14669        }
14670    }
14671
14672    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14673        // Collect all used permissions in the UID
14674        ArraySet<String> usedPermissions = new ArraySet<>();
14675        final int packageCount = su.packages.size();
14676        for (int i = 0; i < packageCount; i++) {
14677            PackageSetting ps = su.packages.valueAt(i);
14678            if (ps.pkg == null) {
14679                continue;
14680            }
14681            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14682            for (int j = 0; j < requestedPermCount; j++) {
14683                String permission = ps.pkg.requestedPermissions.get(j);
14684                BasePermission bp = mSettings.mPermissions.get(permission);
14685                if (bp != null) {
14686                    usedPermissions.add(permission);
14687                }
14688            }
14689        }
14690
14691        PermissionsState permissionsState = su.getPermissionsState();
14692        // Prune install permissions
14693        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14694        final int installPermCount = installPermStates.size();
14695        for (int i = installPermCount - 1; i >= 0;  i--) {
14696            PermissionState permissionState = installPermStates.get(i);
14697            if (!usedPermissions.contains(permissionState.getName())) {
14698                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14699                if (bp != null) {
14700                    permissionsState.revokeInstallPermission(bp);
14701                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14702                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14703                }
14704            }
14705        }
14706
14707        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14708
14709        // Prune runtime permissions
14710        for (int userId : allUserIds) {
14711            List<PermissionState> runtimePermStates = permissionsState
14712                    .getRuntimePermissionStates(userId);
14713            final int runtimePermCount = runtimePermStates.size();
14714            for (int i = runtimePermCount - 1; i >= 0; i--) {
14715                PermissionState permissionState = runtimePermStates.get(i);
14716                if (!usedPermissions.contains(permissionState.getName())) {
14717                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14718                    if (bp != null) {
14719                        permissionsState.revokeRuntimePermission(bp, userId);
14720                        permissionsState.updatePermissionFlags(bp, userId,
14721                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14722                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14723                                runtimePermissionChangedUserIds, userId);
14724                    }
14725                }
14726            }
14727        }
14728
14729        return runtimePermissionChangedUserIds;
14730    }
14731
14732    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14733            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14734        // Update the parent package setting
14735        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14736                res, user);
14737        // Update the child packages setting
14738        final int childCount = (newPackage.childPackages != null)
14739                ? newPackage.childPackages.size() : 0;
14740        for (int i = 0; i < childCount; i++) {
14741            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14742            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14743            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14744                    childRes.origUsers, childRes, user);
14745        }
14746    }
14747
14748    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14749            String installerPackageName, int[] allUsers, int[] installedForUsers,
14750            PackageInstalledInfo res, UserHandle user) {
14751        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14752
14753        String pkgName = newPackage.packageName;
14754        synchronized (mPackages) {
14755            //write settings. the installStatus will be incomplete at this stage.
14756            //note that the new package setting would have already been
14757            //added to mPackages. It hasn't been persisted yet.
14758            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14759            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14760            mSettings.writeLPr();
14761            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14762        }
14763
14764        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14765        synchronized (mPackages) {
14766            updatePermissionsLPw(newPackage.packageName, newPackage,
14767                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14768                            ? UPDATE_PERMISSIONS_ALL : 0));
14769            // For system-bundled packages, we assume that installing an upgraded version
14770            // of the package implies that the user actually wants to run that new code,
14771            // so we enable the package.
14772            PackageSetting ps = mSettings.mPackages.get(pkgName);
14773            final int userId = user.getIdentifier();
14774            if (ps != null) {
14775                if (isSystemApp(newPackage)) {
14776                    if (DEBUG_INSTALL) {
14777                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14778                    }
14779                    // Enable system package for requested users
14780                    if (res.origUsers != null) {
14781                        for (int origUserId : res.origUsers) {
14782                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14783                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14784                                        origUserId, installerPackageName);
14785                            }
14786                        }
14787                    }
14788                    // Also convey the prior install/uninstall state
14789                    if (allUsers != null && installedForUsers != null) {
14790                        for (int currentUserId : allUsers) {
14791                            final boolean installed = ArrayUtils.contains(
14792                                    installedForUsers, currentUserId);
14793                            if (DEBUG_INSTALL) {
14794                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14795                            }
14796                            ps.setInstalled(installed, currentUserId);
14797                        }
14798                        // these install state changes will be persisted in the
14799                        // upcoming call to mSettings.writeLPr().
14800                    }
14801                }
14802                // It's implied that when a user requests installation, they want the app to be
14803                // installed and enabled.
14804                if (userId != UserHandle.USER_ALL) {
14805                    ps.setInstalled(true, userId);
14806                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14807                }
14808            }
14809            res.name = pkgName;
14810            res.uid = newPackage.applicationInfo.uid;
14811            res.pkg = newPackage;
14812            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14813            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14814            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14815            //to update install status
14816            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14817            mSettings.writeLPr();
14818            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14819        }
14820
14821        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14822    }
14823
14824    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14825        try {
14826            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14827            installPackageLI(args, res);
14828        } finally {
14829            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14830        }
14831    }
14832
14833    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14834        final int installFlags = args.installFlags;
14835        final String installerPackageName = args.installerPackageName;
14836        final String volumeUuid = args.volumeUuid;
14837        final File tmpPackageFile = new File(args.getCodePath());
14838        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14839        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14840                || (args.volumeUuid != null));
14841        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14842        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
14843        boolean replace = false;
14844        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14845        if (args.move != null) {
14846            // moving a complete application; perform an initial scan on the new install location
14847            scanFlags |= SCAN_INITIAL;
14848        }
14849        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14850            scanFlags |= SCAN_DONT_KILL_APP;
14851        }
14852
14853        // Result object to be returned
14854        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14855
14856        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14857
14858        // Sanity check
14859        if (ephemeral && (forwardLocked || onExternal)) {
14860            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14861                    + " external=" + onExternal);
14862            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14863            return;
14864        }
14865
14866        // Retrieve PackageSettings and parse package
14867        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14868                | PackageParser.PARSE_ENFORCE_CODE
14869                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14870                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14871                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0)
14872                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
14873        PackageParser pp = new PackageParser();
14874        pp.setSeparateProcesses(mSeparateProcesses);
14875        pp.setDisplayMetrics(mMetrics);
14876
14877        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14878        final PackageParser.Package pkg;
14879        try {
14880            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14881        } catch (PackageParserException e) {
14882            res.setError("Failed parse during installPackageLI", e);
14883            return;
14884        } finally {
14885            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14886        }
14887
14888        // If we are installing a clustered package add results for the children
14889        if (pkg.childPackages != null) {
14890            synchronized (mPackages) {
14891                final int childCount = pkg.childPackages.size();
14892                for (int i = 0; i < childCount; i++) {
14893                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14894                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14895                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14896                    childRes.pkg = childPkg;
14897                    childRes.name = childPkg.packageName;
14898                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14899                    if (childPs != null) {
14900                        childRes.origUsers = childPs.queryInstalledUsers(
14901                                sUserManager.getUserIds(), true);
14902                    }
14903                    if ((mPackages.containsKey(childPkg.packageName))) {
14904                        childRes.removedInfo = new PackageRemovedInfo();
14905                        childRes.removedInfo.removedPackage = childPkg.packageName;
14906                    }
14907                    if (res.addedChildPackages == null) {
14908                        res.addedChildPackages = new ArrayMap<>();
14909                    }
14910                    res.addedChildPackages.put(childPkg.packageName, childRes);
14911                }
14912            }
14913        }
14914
14915        // If package doesn't declare API override, mark that we have an install
14916        // time CPU ABI override.
14917        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14918            pkg.cpuAbiOverride = args.abiOverride;
14919        }
14920
14921        String pkgName = res.name = pkg.packageName;
14922        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14923            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14924                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14925                return;
14926            }
14927        }
14928
14929        try {
14930            // either use what we've been given or parse directly from the APK
14931            if (args.certificates != null) {
14932                try {
14933                    PackageParser.populateCertificates(pkg, args.certificates);
14934                } catch (PackageParserException e) {
14935                    // there was something wrong with the certificates we were given;
14936                    // try to pull them from the APK
14937                    PackageParser.collectCertificates(pkg, parseFlags);
14938                }
14939            } else {
14940                PackageParser.collectCertificates(pkg, parseFlags);
14941            }
14942        } catch (PackageParserException e) {
14943            res.setError("Failed collect during installPackageLI", e);
14944            return;
14945        }
14946
14947        // Get rid of all references to package scan path via parser.
14948        pp = null;
14949        String oldCodePath = null;
14950        boolean systemApp = false;
14951        synchronized (mPackages) {
14952            // Check if installing already existing package
14953            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14954                String oldName = mSettings.mRenamedPackages.get(pkgName);
14955                if (pkg.mOriginalPackages != null
14956                        && pkg.mOriginalPackages.contains(oldName)
14957                        && mPackages.containsKey(oldName)) {
14958                    // This package is derived from an original package,
14959                    // and this device has been updating from that original
14960                    // name.  We must continue using the original name, so
14961                    // rename the new package here.
14962                    pkg.setPackageName(oldName);
14963                    pkgName = pkg.packageName;
14964                    replace = true;
14965                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14966                            + oldName + " pkgName=" + pkgName);
14967                } else if (mPackages.containsKey(pkgName)) {
14968                    // This package, under its official name, already exists
14969                    // on the device; we should replace it.
14970                    replace = true;
14971                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14972                }
14973
14974                // Child packages are installed through the parent package
14975                if (pkg.parentPackage != null) {
14976                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14977                            "Package " + pkg.packageName + " is child of package "
14978                                    + pkg.parentPackage.parentPackage + ". Child packages "
14979                                    + "can be updated only through the parent package.");
14980                    return;
14981                }
14982
14983                if (replace) {
14984                    // Prevent apps opting out from runtime permissions
14985                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14986                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14987                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14988                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14989                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14990                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14991                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14992                                        + " doesn't support runtime permissions but the old"
14993                                        + " target SDK " + oldTargetSdk + " does.");
14994                        return;
14995                    }
14996
14997                    // Prevent installing of child packages
14998                    if (oldPackage.parentPackage != null) {
14999                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
15000                                "Package " + pkg.packageName + " is child of package "
15001                                        + oldPackage.parentPackage + ". Child packages "
15002                                        + "can be updated only through the parent package.");
15003                        return;
15004                    }
15005                }
15006            }
15007
15008            PackageSetting ps = mSettings.mPackages.get(pkgName);
15009            if (ps != null) {
15010                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
15011
15012                // Quick sanity check that we're signed correctly if updating;
15013                // we'll check this again later when scanning, but we want to
15014                // bail early here before tripping over redefined permissions.
15015                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
15016                    if (!checkUpgradeKeySetLP(ps, pkg)) {
15017                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
15018                                + pkg.packageName + " upgrade keys do not match the "
15019                                + "previously installed version");
15020                        return;
15021                    }
15022                } else {
15023                    try {
15024                        verifySignaturesLP(ps, pkg);
15025                    } catch (PackageManagerException e) {
15026                        res.setError(e.error, e.getMessage());
15027                        return;
15028                    }
15029                }
15030
15031                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
15032                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
15033                    systemApp = (ps.pkg.applicationInfo.flags &
15034                            ApplicationInfo.FLAG_SYSTEM) != 0;
15035                }
15036                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15037            }
15038
15039            // Check whether the newly-scanned package wants to define an already-defined perm
15040            int N = pkg.permissions.size();
15041            for (int i = N-1; i >= 0; i--) {
15042                PackageParser.Permission perm = pkg.permissions.get(i);
15043                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
15044                if (bp != null) {
15045                    // If the defining package is signed with our cert, it's okay.  This
15046                    // also includes the "updating the same package" case, of course.
15047                    // "updating same package" could also involve key-rotation.
15048                    final boolean sigsOk;
15049                    if (bp.sourcePackage.equals(pkg.packageName)
15050                            && (bp.packageSetting instanceof PackageSetting)
15051                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
15052                                    scanFlags))) {
15053                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
15054                    } else {
15055                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
15056                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
15057                    }
15058                    if (!sigsOk) {
15059                        // If the owning package is the system itself, we log but allow
15060                        // install to proceed; we fail the install on all other permission
15061                        // redefinitions.
15062                        if (!bp.sourcePackage.equals("android")) {
15063                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
15064                                    + pkg.packageName + " attempting to redeclare permission "
15065                                    + perm.info.name + " already owned by " + bp.sourcePackage);
15066                            res.origPermission = perm.info.name;
15067                            res.origPackage = bp.sourcePackage;
15068                            return;
15069                        } else {
15070                            Slog.w(TAG, "Package " + pkg.packageName
15071                                    + " attempting to redeclare system permission "
15072                                    + perm.info.name + "; ignoring new declaration");
15073                            pkg.permissions.remove(i);
15074                        }
15075                    }
15076                }
15077            }
15078        }
15079
15080        if (systemApp) {
15081            if (onExternal) {
15082                // Abort update; system app can't be replaced with app on sdcard
15083                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
15084                        "Cannot install updates to system apps on sdcard");
15085                return;
15086            } else if (ephemeral) {
15087                // Abort update; system app can't be replaced with an ephemeral app
15088                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
15089                        "Cannot update a system app with an ephemeral app");
15090                return;
15091            }
15092        }
15093
15094        if (args.move != null) {
15095            // We did an in-place move, so dex is ready to roll
15096            scanFlags |= SCAN_NO_DEX;
15097            scanFlags |= SCAN_MOVE;
15098
15099            synchronized (mPackages) {
15100                final PackageSetting ps = mSettings.mPackages.get(pkgName);
15101                if (ps == null) {
15102                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
15103                            "Missing settings for moved package " + pkgName);
15104                }
15105
15106                // We moved the entire application as-is, so bring over the
15107                // previously derived ABI information.
15108                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
15109                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
15110            }
15111
15112        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
15113            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
15114            scanFlags |= SCAN_NO_DEX;
15115
15116            try {
15117                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
15118                    args.abiOverride : pkg.cpuAbiOverride);
15119                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
15120                        true /* extract libs */);
15121            } catch (PackageManagerException pme) {
15122                Slog.e(TAG, "Error deriving application ABI", pme);
15123                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
15124                return;
15125            }
15126
15127            // Shared libraries for the package need to be updated.
15128            synchronized (mPackages) {
15129                try {
15130                    updateSharedLibrariesLPw(pkg, null);
15131                } catch (PackageManagerException e) {
15132                    Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage());
15133                }
15134            }
15135            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
15136            // Do not run PackageDexOptimizer through the local performDexOpt
15137            // method because `pkg` is not in `mPackages` yet.
15138            int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
15139                    null /* instructionSets */, false /* checkProfiles */,
15140                    getCompilerFilterForReason(REASON_INSTALL));
15141            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15142            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
15143                String msg = "Extracting package failed for " + pkgName;
15144                res.setError(INSTALL_FAILED_DEXOPT, msg);
15145                return;
15146            }
15147
15148            // Notify BackgroundDexOptService that the package has been changed.
15149            // If this is an update of a package which used to fail to compile,
15150            // BDOS will remove it from its blacklist.
15151            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
15152        }
15153
15154        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
15155            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
15156            return;
15157        }
15158
15159        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
15160
15161        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
15162                "installPackageLI")) {
15163            if (replace) {
15164                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
15165                        installerPackageName, res);
15166            } else {
15167                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
15168                        args.user, installerPackageName, volumeUuid, res);
15169            }
15170        }
15171        synchronized (mPackages) {
15172            final PackageSetting ps = mSettings.mPackages.get(pkgName);
15173            if (ps != null) {
15174                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
15175            }
15176
15177            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15178            for (int i = 0; i < childCount; i++) {
15179                PackageParser.Package childPkg = pkg.childPackages.get(i);
15180                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
15181                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
15182                if (childPs != null) {
15183                    childRes.newUsers = childPs.queryInstalledUsers(
15184                            sUserManager.getUserIds(), true);
15185                }
15186            }
15187        }
15188    }
15189
15190    private void startIntentFilterVerifications(int userId, boolean replacing,
15191            PackageParser.Package pkg) {
15192        if (mIntentFilterVerifierComponent == null) {
15193            Slog.w(TAG, "No IntentFilter verification will not be done as "
15194                    + "there is no IntentFilterVerifier available!");
15195            return;
15196        }
15197
15198        final int verifierUid = getPackageUid(
15199                mIntentFilterVerifierComponent.getPackageName(),
15200                MATCH_DEBUG_TRIAGED_MISSING,
15201                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
15202
15203        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15204        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
15205        mHandler.sendMessage(msg);
15206
15207        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
15208        for (int i = 0; i < childCount; i++) {
15209            PackageParser.Package childPkg = pkg.childPackages.get(i);
15210            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
15211            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
15212            mHandler.sendMessage(msg);
15213        }
15214    }
15215
15216    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
15217            PackageParser.Package pkg) {
15218        int size = pkg.activities.size();
15219        if (size == 0) {
15220            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15221                    "No activity, so no need to verify any IntentFilter!");
15222            return;
15223        }
15224
15225        final boolean hasDomainURLs = hasDomainURLs(pkg);
15226        if (!hasDomainURLs) {
15227            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15228                    "No domain URLs, so no need to verify any IntentFilter!");
15229            return;
15230        }
15231
15232        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
15233                + " if any IntentFilter from the " + size
15234                + " Activities needs verification ...");
15235
15236        int count = 0;
15237        final String packageName = pkg.packageName;
15238
15239        synchronized (mPackages) {
15240            // If this is a new install and we see that we've already run verification for this
15241            // package, we have nothing to do: it means the state was restored from backup.
15242            if (!replacing) {
15243                IntentFilterVerificationInfo ivi =
15244                        mSettings.getIntentFilterVerificationLPr(packageName);
15245                if (ivi != null) {
15246                    if (DEBUG_DOMAIN_VERIFICATION) {
15247                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
15248                                + ivi.getStatusString());
15249                    }
15250                    return;
15251                }
15252            }
15253
15254            // If any filters need to be verified, then all need to be.
15255            boolean needToVerify = false;
15256            for (PackageParser.Activity a : pkg.activities) {
15257                for (ActivityIntentInfo filter : a.intents) {
15258                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
15259                        if (DEBUG_DOMAIN_VERIFICATION) {
15260                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
15261                        }
15262                        needToVerify = true;
15263                        break;
15264                    }
15265                }
15266            }
15267
15268            if (needToVerify) {
15269                final int verificationId = mIntentFilterVerificationToken++;
15270                for (PackageParser.Activity a : pkg.activities) {
15271                    for (ActivityIntentInfo filter : a.intents) {
15272                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
15273                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
15274                                    "Verification needed for IntentFilter:" + filter.toString());
15275                            mIntentFilterVerifier.addOneIntentFilterVerification(
15276                                    verifierUid, userId, verificationId, filter, packageName);
15277                            count++;
15278                        }
15279                    }
15280                }
15281            }
15282        }
15283
15284        if (count > 0) {
15285            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
15286                    + " IntentFilter verification" + (count > 1 ? "s" : "")
15287                    +  " for userId:" + userId);
15288            mIntentFilterVerifier.startVerifications(userId);
15289        } else {
15290            if (DEBUG_DOMAIN_VERIFICATION) {
15291                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
15292            }
15293        }
15294    }
15295
15296    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
15297        final ComponentName cn  = filter.activity.getComponentName();
15298        final String packageName = cn.getPackageName();
15299
15300        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
15301                packageName);
15302        if (ivi == null) {
15303            return true;
15304        }
15305        int status = ivi.getStatus();
15306        switch (status) {
15307            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
15308            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
15309                return true;
15310
15311            default:
15312                // Nothing to do
15313                return false;
15314        }
15315    }
15316
15317    private static boolean isMultiArch(ApplicationInfo info) {
15318        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
15319    }
15320
15321    private static boolean isExternal(PackageParser.Package pkg) {
15322        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15323    }
15324
15325    private static boolean isExternal(PackageSetting ps) {
15326        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
15327    }
15328
15329    private static boolean isEphemeral(PackageParser.Package pkg) {
15330        return pkg.applicationInfo.isEphemeralApp();
15331    }
15332
15333    private static boolean isEphemeral(PackageSetting ps) {
15334        return ps.pkg != null && isEphemeral(ps.pkg);
15335    }
15336
15337    private static boolean isSystemApp(PackageParser.Package pkg) {
15338        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
15339    }
15340
15341    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
15342        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
15343    }
15344
15345    private static boolean hasDomainURLs(PackageParser.Package pkg) {
15346        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
15347    }
15348
15349    private static boolean isSystemApp(PackageSetting ps) {
15350        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
15351    }
15352
15353    private static boolean isUpdatedSystemApp(PackageSetting ps) {
15354        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
15355    }
15356
15357    private int packageFlagsToInstallFlags(PackageSetting ps) {
15358        int installFlags = 0;
15359        if (isEphemeral(ps)) {
15360            installFlags |= PackageManager.INSTALL_EPHEMERAL;
15361        }
15362        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
15363            // This existing package was an external ASEC install when we have
15364            // the external flag without a UUID
15365            installFlags |= PackageManager.INSTALL_EXTERNAL;
15366        }
15367        if (ps.isForwardLocked()) {
15368            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
15369        }
15370        return installFlags;
15371    }
15372
15373    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
15374        if (isExternal(pkg)) {
15375            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15376                return StorageManager.UUID_PRIMARY_PHYSICAL;
15377            } else {
15378                return pkg.volumeUuid;
15379            }
15380        } else {
15381            return StorageManager.UUID_PRIVATE_INTERNAL;
15382        }
15383    }
15384
15385    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
15386        if (isExternal(pkg)) {
15387            if (TextUtils.isEmpty(pkg.volumeUuid)) {
15388                return mSettings.getExternalVersion();
15389            } else {
15390                return mSettings.findOrCreateVersion(pkg.volumeUuid);
15391            }
15392        } else {
15393            return mSettings.getInternalVersion();
15394        }
15395    }
15396
15397    private void deleteTempPackageFiles() {
15398        final FilenameFilter filter = new FilenameFilter() {
15399            public boolean accept(File dir, String name) {
15400                return name.startsWith("vmdl") && name.endsWith(".tmp");
15401            }
15402        };
15403        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
15404            file.delete();
15405        }
15406    }
15407
15408    @Override
15409    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
15410            int flags) {
15411        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
15412                flags);
15413    }
15414
15415    @Override
15416    public void deletePackage(final String packageName,
15417            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
15418        mContext.enforceCallingOrSelfPermission(
15419                android.Manifest.permission.DELETE_PACKAGES, null);
15420        Preconditions.checkNotNull(packageName);
15421        Preconditions.checkNotNull(observer);
15422        final int uid = Binder.getCallingUid();
15423        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
15424        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
15425        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
15426            mContext.enforceCallingOrSelfPermission(
15427                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
15428                    "deletePackage for user " + userId);
15429        }
15430
15431        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
15432            try {
15433                observer.onPackageDeleted(packageName,
15434                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
15435            } catch (RemoteException re) {
15436            }
15437            return;
15438        }
15439
15440        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
15441            try {
15442                observer.onPackageDeleted(packageName,
15443                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
15444            } catch (RemoteException re) {
15445            }
15446            return;
15447        }
15448
15449        if (DEBUG_REMOVE) {
15450            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
15451                    + " deleteAllUsers: " + deleteAllUsers );
15452        }
15453        // Queue up an async operation since the package deletion may take a little while.
15454        mHandler.post(new Runnable() {
15455            public void run() {
15456                mHandler.removeCallbacks(this);
15457                int returnCode;
15458                if (!deleteAllUsers) {
15459                    returnCode = deletePackageX(packageName, userId, deleteFlags);
15460                } else {
15461                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
15462                    // If nobody is blocking uninstall, proceed with delete for all users
15463                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
15464                        returnCode = deletePackageX(packageName, userId, deleteFlags);
15465                    } else {
15466                        // Otherwise uninstall individually for users with blockUninstalls=false
15467                        final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
15468                        for (int userId : users) {
15469                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
15470                                returnCode = deletePackageX(packageName, userId, userFlags);
15471                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
15472                                    Slog.w(TAG, "Package delete failed for user " + userId
15473                                            + ", returnCode " + returnCode);
15474                                }
15475                            }
15476                        }
15477                        // The app has only been marked uninstalled for certain users.
15478                        // We still need to report that delete was blocked
15479                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
15480                    }
15481                }
15482                try {
15483                    observer.onPackageDeleted(packageName, returnCode, null);
15484                } catch (RemoteException e) {
15485                    Log.i(TAG, "Observer no longer exists.");
15486                } //end catch
15487            } //end run
15488        });
15489    }
15490
15491    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
15492        int[] result = EMPTY_INT_ARRAY;
15493        for (int userId : userIds) {
15494            if (getBlockUninstallForUser(packageName, userId)) {
15495                result = ArrayUtils.appendInt(result, userId);
15496            }
15497        }
15498        return result;
15499    }
15500
15501    @Override
15502    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
15503        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
15504    }
15505
15506    private boolean isPackageDeviceAdmin(String packageName, int userId) {
15507        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
15508                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
15509        try {
15510            if (dpm != null) {
15511                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
15512                        /* callingUserOnly =*/ false);
15513                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
15514                        : deviceOwnerComponentName.getPackageName();
15515                // Does the package contains the device owner?
15516                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
15517                // this check is probably not needed, since DO should be registered as a device
15518                // admin on some user too. (Original bug for this: b/17657954)
15519                if (packageName.equals(deviceOwnerPackageName)) {
15520                    return true;
15521                }
15522                // Does it contain a device admin for any user?
15523                int[] users;
15524                if (userId == UserHandle.USER_ALL) {
15525                    users = sUserManager.getUserIds();
15526                } else {
15527                    users = new int[]{userId};
15528                }
15529                for (int i = 0; i < users.length; ++i) {
15530                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
15531                        return true;
15532                    }
15533                }
15534            }
15535        } catch (RemoteException e) {
15536        }
15537        return false;
15538    }
15539
15540    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
15541        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
15542    }
15543
15544    /**
15545     *  This method is an internal method that could be get invoked either
15546     *  to delete an installed package or to clean up a failed installation.
15547     *  After deleting an installed package, a broadcast is sent to notify any
15548     *  listeners that the package has been removed. For cleaning up a failed
15549     *  installation, the broadcast is not necessary since the package's
15550     *  installation wouldn't have sent the initial broadcast either
15551     *  The key steps in deleting a package are
15552     *  deleting the package information in internal structures like mPackages,
15553     *  deleting the packages base directories through installd
15554     *  updating mSettings to reflect current status
15555     *  persisting settings for later use
15556     *  sending a broadcast if necessary
15557     */
15558    private int deletePackageX(String packageName, int userId, int deleteFlags) {
15559        final PackageRemovedInfo info = new PackageRemovedInfo();
15560        final boolean res;
15561
15562        final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
15563                ? UserHandle.ALL : new UserHandle(userId);
15564
15565        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
15566            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
15567            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
15568        }
15569
15570        PackageSetting uninstalledPs = null;
15571
15572        // for the uninstall-updates case and restricted profiles, remember the per-
15573        // user handle installed state
15574        int[] allUsers;
15575        synchronized (mPackages) {
15576            uninstalledPs = mSettings.mPackages.get(packageName);
15577            if (uninstalledPs == null) {
15578                Slog.w(TAG, "Not removing non-existent package " + packageName);
15579                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15580            }
15581            allUsers = sUserManager.getUserIds();
15582            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
15583        }
15584
15585        synchronized (mInstallLock) {
15586            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
15587            try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags,
15588                    "deletePackageX")) {
15589                res = deletePackageLIF(packageName, removeForUser, true, allUsers,
15590                        deleteFlags | REMOVE_CHATTY, info, true, null);
15591            }
15592            synchronized (mPackages) {
15593                if (res) {
15594                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
15595                }
15596            }
15597        }
15598
15599        if (res) {
15600            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15601            info.sendPackageRemovedBroadcasts(killApp);
15602            info.sendSystemPackageUpdatedBroadcasts();
15603            info.sendSystemPackageAppearedBroadcasts();
15604        }
15605        // Force a gc here.
15606        Runtime.getRuntime().gc();
15607        // Delete the resources here after sending the broadcast to let
15608        // other processes clean up before deleting resources.
15609        if (info.args != null) {
15610            synchronized (mInstallLock) {
15611                info.args.doPostDeleteLI(true);
15612            }
15613        }
15614
15615        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
15616    }
15617
15618    class PackageRemovedInfo {
15619        String removedPackage;
15620        int uid = -1;
15621        int removedAppId = -1;
15622        int[] origUsers;
15623        int[] removedUsers = null;
15624        boolean isRemovedPackageSystemUpdate = false;
15625        boolean isUpdate;
15626        boolean dataRemoved;
15627        boolean removedForAllUsers;
15628        // Clean up resources deleted packages.
15629        InstallArgs args = null;
15630        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
15631        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
15632
15633        void sendPackageRemovedBroadcasts(boolean killApp) {
15634            sendPackageRemovedBroadcastInternal(killApp);
15635            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
15636            for (int i = 0; i < childCount; i++) {
15637                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15638                childInfo.sendPackageRemovedBroadcastInternal(killApp);
15639            }
15640        }
15641
15642        void sendSystemPackageUpdatedBroadcasts() {
15643            if (isRemovedPackageSystemUpdate) {
15644                sendSystemPackageUpdatedBroadcastsInternal();
15645                final int childCount = (removedChildPackages != null)
15646                        ? removedChildPackages.size() : 0;
15647                for (int i = 0; i < childCount; i++) {
15648                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
15649                    if (childInfo.isRemovedPackageSystemUpdate) {
15650                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
15651                    }
15652                }
15653            }
15654        }
15655
15656        void sendSystemPackageAppearedBroadcasts() {
15657            final int packageCount = (appearedChildPackages != null)
15658                    ? appearedChildPackages.size() : 0;
15659            for (int i = 0; i < packageCount; i++) {
15660                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
15661                for (int userId : installedInfo.newUsers) {
15662                    sendPackageAddedForUser(installedInfo.name, true,
15663                            UserHandle.getAppId(installedInfo.uid), userId);
15664                }
15665            }
15666        }
15667
15668        private void sendSystemPackageUpdatedBroadcastsInternal() {
15669            Bundle extras = new Bundle(2);
15670            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
15671            extras.putBoolean(Intent.EXTRA_REPLACING, true);
15672            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
15673                    extras, 0, null, null, null);
15674            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
15675                    extras, 0, null, null, null);
15676            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
15677                    null, 0, removedPackage, null, null);
15678        }
15679
15680        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
15681            Bundle extras = new Bundle(2);
15682            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
15683            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
15684            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
15685            if (isUpdate || isRemovedPackageSystemUpdate) {
15686                extras.putBoolean(Intent.EXTRA_REPLACING, true);
15687            }
15688            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
15689            if (removedPackage != null) {
15690                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
15691                        extras, 0, null, null, removedUsers);
15692                if (dataRemoved && !isRemovedPackageSystemUpdate) {
15693                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
15694                            removedPackage, extras, 0, null, null, removedUsers);
15695                }
15696            }
15697            if (removedAppId >= 0) {
15698                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
15699                        removedUsers);
15700            }
15701        }
15702    }
15703
15704    /*
15705     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15706     * flag is not set, the data directory is removed as well.
15707     * make sure this flag is set for partially installed apps. If not its meaningless to
15708     * delete a partially installed application.
15709     */
15710    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
15711            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15712        String packageName = ps.name;
15713        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15714        // Retrieve object to delete permissions for shared user later on
15715        final PackageParser.Package deletedPkg;
15716        final PackageSetting deletedPs;
15717        // reader
15718        synchronized (mPackages) {
15719            deletedPkg = mPackages.get(packageName);
15720            deletedPs = mSettings.mPackages.get(packageName);
15721            if (outInfo != null) {
15722                outInfo.removedPackage = packageName;
15723                outInfo.removedUsers = deletedPs != null
15724                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15725                        : null;
15726            }
15727        }
15728
15729        removePackageLI(ps, (flags & REMOVE_CHATTY) != 0);
15730
15731        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
15732            final PackageParser.Package resolvedPkg;
15733            if (deletedPkg != null) {
15734                resolvedPkg = deletedPkg;
15735            } else {
15736                // We don't have a parsed package when it lives on an ejected
15737                // adopted storage device, so fake something together
15738                resolvedPkg = new PackageParser.Package(ps.name);
15739                resolvedPkg.setVolumeUuid(ps.volumeUuid);
15740            }
15741            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
15742                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
15743            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
15744            if (outInfo != null) {
15745                outInfo.dataRemoved = true;
15746            }
15747            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15748        }
15749
15750        // writer
15751        synchronized (mPackages) {
15752            if (deletedPs != null) {
15753                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15754                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15755                    clearDefaultBrowserIfNeeded(packageName);
15756                    if (outInfo != null) {
15757                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15758                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15759                    }
15760                    updatePermissionsLPw(deletedPs.name, null, 0);
15761                    if (deletedPs.sharedUser != null) {
15762                        // Remove permissions associated with package. Since runtime
15763                        // permissions are per user we have to kill the removed package
15764                        // or packages running under the shared user of the removed
15765                        // package if revoking the permissions requested only by the removed
15766                        // package is successful and this causes a change in gids.
15767                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15768                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15769                                    userId);
15770                            if (userIdToKill == UserHandle.USER_ALL
15771                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15772                                // If gids changed for this user, kill all affected packages.
15773                                mHandler.post(new Runnable() {
15774                                    @Override
15775                                    public void run() {
15776                                        // This has to happen with no lock held.
15777                                        killApplication(deletedPs.name, deletedPs.appId,
15778                                                KILL_APP_REASON_GIDS_CHANGED);
15779                                    }
15780                                });
15781                                break;
15782                            }
15783                        }
15784                    }
15785                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15786                }
15787                // make sure to preserve per-user disabled state if this removal was just
15788                // a downgrade of a system app to the factory package
15789                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15790                    if (DEBUG_REMOVE) {
15791                        Slog.d(TAG, "Propagating install state across downgrade");
15792                    }
15793                    for (int userId : allUserHandles) {
15794                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15795                        if (DEBUG_REMOVE) {
15796                            Slog.d(TAG, "    user " + userId + " => " + installed);
15797                        }
15798                        ps.setInstalled(installed, userId);
15799                    }
15800                }
15801            }
15802            // can downgrade to reader
15803            if (writeSettings) {
15804                // Save settings now
15805                mSettings.writeLPr();
15806            }
15807        }
15808        if (outInfo != null) {
15809            // A user ID was deleted here. Go through all users and remove it
15810            // from KeyStore.
15811            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15812        }
15813    }
15814
15815    static boolean locationIsPrivileged(File path) {
15816        try {
15817            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15818                    .getCanonicalPath();
15819            return path.getCanonicalPath().startsWith(privilegedAppDir);
15820        } catch (IOException e) {
15821            Slog.e(TAG, "Unable to access code path " + path);
15822        }
15823        return false;
15824    }
15825
15826    /*
15827     * Tries to delete system package.
15828     */
15829    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
15830            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15831            boolean writeSettings) {
15832        if (deletedPs.parentPackageName != null) {
15833            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15834            return false;
15835        }
15836
15837        final boolean applyUserRestrictions
15838                = (allUserHandles != null) && (outInfo.origUsers != null);
15839        final PackageSetting disabledPs;
15840        // Confirm if the system package has been updated
15841        // An updated system app can be deleted. This will also have to restore
15842        // the system pkg from system partition
15843        // reader
15844        synchronized (mPackages) {
15845            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15846        }
15847
15848        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15849                + " disabledPs=" + disabledPs);
15850
15851        if (disabledPs == null) {
15852            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15853            return false;
15854        } else if (DEBUG_REMOVE) {
15855            Slog.d(TAG, "Deleting system pkg from data partition");
15856        }
15857
15858        if (DEBUG_REMOVE) {
15859            if (applyUserRestrictions) {
15860                Slog.d(TAG, "Remembering install states:");
15861                for (int userId : allUserHandles) {
15862                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15863                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15864                }
15865            }
15866        }
15867
15868        // Delete the updated package
15869        outInfo.isRemovedPackageSystemUpdate = true;
15870        if (outInfo.removedChildPackages != null) {
15871            final int childCount = (deletedPs.childPackageNames != null)
15872                    ? deletedPs.childPackageNames.size() : 0;
15873            for (int i = 0; i < childCount; i++) {
15874                String childPackageName = deletedPs.childPackageNames.get(i);
15875                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15876                        .contains(childPackageName)) {
15877                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15878                            childPackageName);
15879                    if (childInfo != null) {
15880                        childInfo.isRemovedPackageSystemUpdate = true;
15881                    }
15882                }
15883            }
15884        }
15885
15886        if (disabledPs.versionCode < deletedPs.versionCode) {
15887            // Delete data for downgrades
15888            flags &= ~PackageManager.DELETE_KEEP_DATA;
15889        } else {
15890            // Preserve data by setting flag
15891            flags |= PackageManager.DELETE_KEEP_DATA;
15892        }
15893
15894        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
15895                outInfo, writeSettings, disabledPs.pkg);
15896        if (!ret) {
15897            return false;
15898        }
15899
15900        // writer
15901        synchronized (mPackages) {
15902            // Reinstate the old system package
15903            enableSystemPackageLPw(disabledPs.pkg);
15904            // Remove any native libraries from the upgraded package.
15905            removeNativeBinariesLI(deletedPs);
15906        }
15907
15908        // Install the system package
15909        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15910        int parseFlags = mDefParseFlags
15911                | PackageParser.PARSE_MUST_BE_APK
15912                | PackageParser.PARSE_IS_SYSTEM
15913                | PackageParser.PARSE_IS_SYSTEM_DIR;
15914        if (locationIsPrivileged(disabledPs.codePath)) {
15915            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15916        }
15917
15918        final PackageParser.Package newPkg;
15919        try {
15920            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15921        } catch (PackageManagerException e) {
15922            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15923                    + e.getMessage());
15924            return false;
15925        }
15926
15927        prepareAppDataAfterInstallLIF(newPkg);
15928
15929        // writer
15930        synchronized (mPackages) {
15931            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15932
15933            // Propagate the permissions state as we do not want to drop on the floor
15934            // runtime permissions. The update permissions method below will take
15935            // care of removing obsolete permissions and grant install permissions.
15936            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15937            updatePermissionsLPw(newPkg.packageName, newPkg,
15938                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15939
15940            if (applyUserRestrictions) {
15941                if (DEBUG_REMOVE) {
15942                    Slog.d(TAG, "Propagating install state across reinstall");
15943                }
15944                for (int userId : allUserHandles) {
15945                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15946                    if (DEBUG_REMOVE) {
15947                        Slog.d(TAG, "    user " + userId + " => " + installed);
15948                    }
15949                    ps.setInstalled(installed, userId);
15950
15951                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15952                }
15953                // Regardless of writeSettings we need to ensure that this restriction
15954                // state propagation is persisted
15955                mSettings.writeAllUsersPackageRestrictionsLPr();
15956            }
15957            // can downgrade to reader here
15958            if (writeSettings) {
15959                mSettings.writeLPr();
15960            }
15961        }
15962        return true;
15963    }
15964
15965    private boolean deleteInstalledPackageLIF(PackageSetting ps,
15966            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15967            PackageRemovedInfo outInfo, boolean writeSettings,
15968            PackageParser.Package replacingPackage) {
15969        synchronized (mPackages) {
15970            if (outInfo != null) {
15971                outInfo.uid = ps.appId;
15972            }
15973
15974            if (outInfo != null && outInfo.removedChildPackages != null) {
15975                final int childCount = (ps.childPackageNames != null)
15976                        ? ps.childPackageNames.size() : 0;
15977                for (int i = 0; i < childCount; i++) {
15978                    String childPackageName = ps.childPackageNames.get(i);
15979                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15980                    if (childPs == null) {
15981                        return false;
15982                    }
15983                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15984                            childPackageName);
15985                    if (childInfo != null) {
15986                        childInfo.uid = childPs.appId;
15987                    }
15988                }
15989            }
15990        }
15991
15992        // Delete package data from internal structures and also remove data if flag is set
15993        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
15994
15995        // Delete the child packages data
15996        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15997        for (int i = 0; i < childCount; i++) {
15998            PackageSetting childPs;
15999            synchronized (mPackages) {
16000                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
16001            }
16002            if (childPs != null) {
16003                PackageRemovedInfo childOutInfo = (outInfo != null
16004                        && outInfo.removedChildPackages != null)
16005                        ? outInfo.removedChildPackages.get(childPs.name) : null;
16006                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
16007                        && (replacingPackage != null
16008                        && !replacingPackage.hasChildPackage(childPs.name))
16009                        ? flags & ~DELETE_KEEP_DATA : flags;
16010                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
16011                        deleteFlags, writeSettings);
16012            }
16013        }
16014
16015        // Delete application code and resources only for parent packages
16016        if (ps.parentPackageName == null) {
16017            if (deleteCodeAndResources && (outInfo != null)) {
16018                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
16019                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
16020                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
16021            }
16022        }
16023
16024        return true;
16025    }
16026
16027    @Override
16028    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
16029            int userId) {
16030        mContext.enforceCallingOrSelfPermission(
16031                android.Manifest.permission.DELETE_PACKAGES, null);
16032        synchronized (mPackages) {
16033            PackageSetting ps = mSettings.mPackages.get(packageName);
16034            if (ps == null) {
16035                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
16036                return false;
16037            }
16038            if (!ps.getInstalled(userId)) {
16039                // Can't block uninstall for an app that is not installed or enabled.
16040                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
16041                return false;
16042            }
16043            ps.setBlockUninstall(blockUninstall, userId);
16044            mSettings.writePackageRestrictionsLPr(userId);
16045        }
16046        return true;
16047    }
16048
16049    @Override
16050    public boolean getBlockUninstallForUser(String packageName, int userId) {
16051        synchronized (mPackages) {
16052            PackageSetting ps = mSettings.mPackages.get(packageName);
16053            if (ps == null) {
16054                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
16055                return false;
16056            }
16057            return ps.getBlockUninstall(userId);
16058        }
16059    }
16060
16061    @Override
16062    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
16063        int callingUid = Binder.getCallingUid();
16064        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
16065            throw new SecurityException(
16066                    "setRequiredForSystemUser can only be run by the system or root");
16067        }
16068        synchronized (mPackages) {
16069            PackageSetting ps = mSettings.mPackages.get(packageName);
16070            if (ps == null) {
16071                Log.w(TAG, "Package doesn't exist: " + packageName);
16072                return false;
16073            }
16074            if (systemUserApp) {
16075                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16076            } else {
16077                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
16078            }
16079            mSettings.writeLPr();
16080        }
16081        return true;
16082    }
16083
16084    /*
16085     * This method handles package deletion in general
16086     */
16087    private boolean deletePackageLIF(String packageName, UserHandle user,
16088            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
16089            PackageRemovedInfo outInfo, boolean writeSettings,
16090            PackageParser.Package replacingPackage) {
16091        if (packageName == null) {
16092            Slog.w(TAG, "Attempt to delete null packageName.");
16093            return false;
16094        }
16095
16096        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
16097
16098        PackageSetting ps;
16099
16100        synchronized (mPackages) {
16101            ps = mSettings.mPackages.get(packageName);
16102            if (ps == null) {
16103                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
16104                return false;
16105            }
16106
16107            if (ps.parentPackageName != null && (!isSystemApp(ps)
16108                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
16109                if (DEBUG_REMOVE) {
16110                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
16111                            + ((user == null) ? UserHandle.USER_ALL : user));
16112                }
16113                final int removedUserId = (user != null) ? user.getIdentifier()
16114                        : UserHandle.USER_ALL;
16115                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
16116                    return false;
16117                }
16118                markPackageUninstalledForUserLPw(ps, user);
16119                scheduleWritePackageRestrictionsLocked(user);
16120                return true;
16121            }
16122        }
16123
16124        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
16125                && user.getIdentifier() != UserHandle.USER_ALL)) {
16126            // The caller is asking that the package only be deleted for a single
16127            // user.  To do this, we just mark its uninstalled state and delete
16128            // its data. If this is a system app, we only allow this to happen if
16129            // they have set the special DELETE_SYSTEM_APP which requests different
16130            // semantics than normal for uninstalling system apps.
16131            markPackageUninstalledForUserLPw(ps, user);
16132
16133            if (!isSystemApp(ps)) {
16134                // Do not uninstall the APK if an app should be cached
16135                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
16136                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
16137                    // Other user still have this package installed, so all
16138                    // we need to do is clear this user's data and save that
16139                    // it is uninstalled.
16140                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
16141                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16142                        return false;
16143                    }
16144                    scheduleWritePackageRestrictionsLocked(user);
16145                    return true;
16146                } else {
16147                    // We need to set it back to 'installed' so the uninstall
16148                    // broadcasts will be sent correctly.
16149                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
16150                    ps.setInstalled(true, user.getIdentifier());
16151                }
16152            } else {
16153                // This is a system app, so we assume that the
16154                // other users still have this package installed, so all
16155                // we need to do is clear this user's data and save that
16156                // it is uninstalled.
16157                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
16158                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
16159                    return false;
16160                }
16161                scheduleWritePackageRestrictionsLocked(user);
16162                return true;
16163            }
16164        }
16165
16166        // If we are deleting a composite package for all users, keep track
16167        // of result for each child.
16168        if (ps.childPackageNames != null && outInfo != null) {
16169            synchronized (mPackages) {
16170                final int childCount = ps.childPackageNames.size();
16171                outInfo.removedChildPackages = new ArrayMap<>(childCount);
16172                for (int i = 0; i < childCount; i++) {
16173                    String childPackageName = ps.childPackageNames.get(i);
16174                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
16175                    childInfo.removedPackage = childPackageName;
16176                    outInfo.removedChildPackages.put(childPackageName, childInfo);
16177                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16178                    if (childPs != null) {
16179                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
16180                    }
16181                }
16182            }
16183        }
16184
16185        boolean ret = false;
16186        if (isSystemApp(ps)) {
16187            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
16188            // When an updated system application is deleted we delete the existing resources
16189            // as well and fall back to existing code in system partition
16190            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
16191        } else {
16192            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
16193            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
16194                    outInfo, writeSettings, replacingPackage);
16195        }
16196
16197        // Take a note whether we deleted the package for all users
16198        if (outInfo != null) {
16199            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16200            if (outInfo.removedChildPackages != null) {
16201                synchronized (mPackages) {
16202                    final int childCount = outInfo.removedChildPackages.size();
16203                    for (int i = 0; i < childCount; i++) {
16204                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
16205                        if (childInfo != null) {
16206                            childInfo.removedForAllUsers = mPackages.get(
16207                                    childInfo.removedPackage) == null;
16208                        }
16209                    }
16210                }
16211            }
16212            // If we uninstalled an update to a system app there may be some
16213            // child packages that appeared as they are declared in the system
16214            // app but were not declared in the update.
16215            if (isSystemApp(ps)) {
16216                synchronized (mPackages) {
16217                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
16218                    final int childCount = (updatedPs.childPackageNames != null)
16219                            ? updatedPs.childPackageNames.size() : 0;
16220                    for (int i = 0; i < childCount; i++) {
16221                        String childPackageName = updatedPs.childPackageNames.get(i);
16222                        if (outInfo.removedChildPackages == null
16223                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
16224                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
16225                            if (childPs == null) {
16226                                continue;
16227                            }
16228                            PackageInstalledInfo installRes = new PackageInstalledInfo();
16229                            installRes.name = childPackageName;
16230                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
16231                            installRes.pkg = mPackages.get(childPackageName);
16232                            installRes.uid = childPs.pkg.applicationInfo.uid;
16233                            if (outInfo.appearedChildPackages == null) {
16234                                outInfo.appearedChildPackages = new ArrayMap<>();
16235                            }
16236                            outInfo.appearedChildPackages.put(childPackageName, installRes);
16237                        }
16238                    }
16239                }
16240            }
16241        }
16242
16243        return ret;
16244    }
16245
16246    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
16247        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
16248                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
16249        for (int nextUserId : userIds) {
16250            if (DEBUG_REMOVE) {
16251                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
16252            }
16253            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
16254                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
16255                    false /*hidden*/, false /*suspended*/, null, null, null,
16256                    false /*blockUninstall*/,
16257                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
16258        }
16259    }
16260
16261    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
16262            PackageRemovedInfo outInfo) {
16263        final PackageParser.Package pkg;
16264        synchronized (mPackages) {
16265            pkg = mPackages.get(ps.name);
16266        }
16267
16268        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
16269                : new int[] {userId};
16270        for (int nextUserId : userIds) {
16271            if (DEBUG_REMOVE) {
16272                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
16273                        + nextUserId);
16274            }
16275
16276            destroyAppDataLIF(pkg, userId,
16277                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
16278            destroyAppProfilesLIF(pkg, userId);
16279            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
16280            schedulePackageCleaning(ps.name, nextUserId, false);
16281            synchronized (mPackages) {
16282                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
16283                    scheduleWritePackageRestrictionsLocked(nextUserId);
16284                }
16285                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
16286            }
16287        }
16288
16289        if (outInfo != null) {
16290            outInfo.removedPackage = ps.name;
16291            outInfo.removedAppId = ps.appId;
16292            outInfo.removedUsers = userIds;
16293        }
16294
16295        return true;
16296    }
16297
16298    private final class ClearStorageConnection implements ServiceConnection {
16299        IMediaContainerService mContainerService;
16300
16301        @Override
16302        public void onServiceConnected(ComponentName name, IBinder service) {
16303            synchronized (this) {
16304                mContainerService = IMediaContainerService.Stub.asInterface(service);
16305                notifyAll();
16306            }
16307        }
16308
16309        @Override
16310        public void onServiceDisconnected(ComponentName name) {
16311        }
16312    }
16313
16314    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
16315        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
16316
16317        final boolean mounted;
16318        if (Environment.isExternalStorageEmulated()) {
16319            mounted = true;
16320        } else {
16321            final String status = Environment.getExternalStorageState();
16322
16323            mounted = status.equals(Environment.MEDIA_MOUNTED)
16324                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
16325        }
16326
16327        if (!mounted) {
16328            return;
16329        }
16330
16331        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
16332        int[] users;
16333        if (userId == UserHandle.USER_ALL) {
16334            users = sUserManager.getUserIds();
16335        } else {
16336            users = new int[] { userId };
16337        }
16338        final ClearStorageConnection conn = new ClearStorageConnection();
16339        if (mContext.bindServiceAsUser(
16340                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
16341            try {
16342                for (int curUser : users) {
16343                    long timeout = SystemClock.uptimeMillis() + 5000;
16344                    synchronized (conn) {
16345                        long now;
16346                        while (conn.mContainerService == null &&
16347                                (now = SystemClock.uptimeMillis()) < timeout) {
16348                            try {
16349                                conn.wait(timeout - now);
16350                            } catch (InterruptedException e) {
16351                            }
16352                        }
16353                    }
16354                    if (conn.mContainerService == null) {
16355                        return;
16356                    }
16357
16358                    final UserEnvironment userEnv = new UserEnvironment(curUser);
16359                    clearDirectory(conn.mContainerService,
16360                            userEnv.buildExternalStorageAppCacheDirs(packageName));
16361                    if (allData) {
16362                        clearDirectory(conn.mContainerService,
16363                                userEnv.buildExternalStorageAppDataDirs(packageName));
16364                        clearDirectory(conn.mContainerService,
16365                                userEnv.buildExternalStorageAppMediaDirs(packageName));
16366                    }
16367                }
16368            } finally {
16369                mContext.unbindService(conn);
16370            }
16371        }
16372    }
16373
16374    @Override
16375    public void clearApplicationProfileData(String packageName) {
16376        enforceSystemOrRoot("Only the system can clear all profile data");
16377
16378        final PackageParser.Package pkg;
16379        synchronized (mPackages) {
16380            pkg = mPackages.get(packageName);
16381        }
16382
16383        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
16384            synchronized (mInstallLock) {
16385                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
16386                destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL,
16387                        true /* removeBaseMarker */);
16388            }
16389        }
16390    }
16391
16392    @Override
16393    public void clearApplicationUserData(final String packageName,
16394            final IPackageDataObserver observer, final int userId) {
16395        mContext.enforceCallingOrSelfPermission(
16396                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
16397
16398        enforceCrossUserPermission(Binder.getCallingUid(), userId,
16399                true /* requireFullPermission */, false /* checkShell */, "clear application data");
16400
16401        if (mProtectedPackages.canPackageBeWiped(userId, packageName)) {
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.
17729            if (mProtectedPackages.canPackageStateBeChanged(userId, packageName)) {
17730                throw new SecurityException("Cannot disable a device owner or a profile owner");
17731            }
17732        }
17733
17734        synchronized (mPackages) {
17735            if (uid == Process.SHELL_UID) {
17736                // Shell can only change whole packages between ENABLED and DISABLED_USER states
17737                int oldState = pkgSetting.getEnabled(userId);
17738                if (className == null
17739                    &&
17740                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
17741                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
17742                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
17743                    &&
17744                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17745                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
17746                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
17747                    // ok
17748                } else {
17749                    throw new SecurityException(
17750                            "Shell cannot change component state for " + packageName + "/"
17751                            + className + " to " + newState);
17752                }
17753            }
17754            if (className == null) {
17755                // We're dealing with an application/package level state change
17756                if (pkgSetting.getEnabled(userId) == newState) {
17757                    // Nothing to do
17758                    return;
17759                }
17760                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17761                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17762                    // Don't care about who enables an app.
17763                    callingPackage = null;
17764                }
17765                pkgSetting.setEnabled(newState, userId, callingPackage);
17766                // pkgSetting.pkg.mSetEnabled = newState;
17767            } else {
17768                // We're dealing with a component level state change
17769                // First, verify that this is a valid class name.
17770                PackageParser.Package pkg = pkgSetting.pkg;
17771                if (pkg == null || !pkg.hasComponentClassName(className)) {
17772                    if (pkg != null &&
17773                            pkg.applicationInfo.targetSdkVersion >=
17774                                    Build.VERSION_CODES.JELLY_BEAN) {
17775                        throw new IllegalArgumentException("Component class " + className
17776                                + " does not exist in " + packageName);
17777                    } else {
17778                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17779                                + className + " does not exist in " + packageName);
17780                    }
17781                }
17782                switch (newState) {
17783                case COMPONENT_ENABLED_STATE_ENABLED:
17784                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17785                        return;
17786                    }
17787                    break;
17788                case COMPONENT_ENABLED_STATE_DISABLED:
17789                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17790                        return;
17791                    }
17792                    break;
17793                case COMPONENT_ENABLED_STATE_DEFAULT:
17794                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17795                        return;
17796                    }
17797                    break;
17798                default:
17799                    Slog.e(TAG, "Invalid new component state: " + newState);
17800                    return;
17801                }
17802            }
17803            scheduleWritePackageRestrictionsLocked(userId);
17804            components = mPendingBroadcasts.get(userId, packageName);
17805            final boolean newPackage = components == null;
17806            if (newPackage) {
17807                components = new ArrayList<String>();
17808            }
17809            if (!components.contains(componentName)) {
17810                components.add(componentName);
17811            }
17812            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17813                sendNow = true;
17814                // Purge entry from pending broadcast list if another one exists already
17815                // since we are sending one right away.
17816                mPendingBroadcasts.remove(userId, packageName);
17817            } else {
17818                if (newPackage) {
17819                    mPendingBroadcasts.put(userId, packageName, components);
17820                }
17821                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17822                    // Schedule a message
17823                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17824                }
17825            }
17826        }
17827
17828        long callingId = Binder.clearCallingIdentity();
17829        try {
17830            if (sendNow) {
17831                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17832                sendPackageChangedBroadcast(packageName,
17833                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17834            }
17835        } finally {
17836            Binder.restoreCallingIdentity(callingId);
17837        }
17838    }
17839
17840    @Override
17841    public void flushPackageRestrictionsAsUser(int userId) {
17842        if (!sUserManager.exists(userId)) {
17843            return;
17844        }
17845        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17846                false /* checkShell */, "flushPackageRestrictions");
17847        synchronized (mPackages) {
17848            mSettings.writePackageRestrictionsLPr(userId);
17849            mDirtyUsers.remove(userId);
17850            if (mDirtyUsers.isEmpty()) {
17851                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17852            }
17853        }
17854    }
17855
17856    private void sendPackageChangedBroadcast(String packageName,
17857            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17858        if (DEBUG_INSTALL)
17859            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17860                    + componentNames);
17861        Bundle extras = new Bundle(4);
17862        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17863        String nameList[] = new String[componentNames.size()];
17864        componentNames.toArray(nameList);
17865        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17866        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17867        extras.putInt(Intent.EXTRA_UID, packageUid);
17868        // If this is not reporting a change of the overall package, then only send it
17869        // to registered receivers.  We don't want to launch a swath of apps for every
17870        // little component state change.
17871        final int flags = !componentNames.contains(packageName)
17872                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17873        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17874                new int[] {UserHandle.getUserId(packageUid)});
17875    }
17876
17877    @Override
17878    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17879        if (!sUserManager.exists(userId)) return;
17880        final int uid = Binder.getCallingUid();
17881        final int permission = mContext.checkCallingOrSelfPermission(
17882                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17883        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17884        enforceCrossUserPermission(uid, userId,
17885                true /* requireFullPermission */, true /* checkShell */, "stop package");
17886        // writer
17887        synchronized (mPackages) {
17888            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17889                    allowedByPermission, uid, userId)) {
17890                scheduleWritePackageRestrictionsLocked(userId);
17891            }
17892        }
17893    }
17894
17895    @Override
17896    public String getInstallerPackageName(String packageName) {
17897        // reader
17898        synchronized (mPackages) {
17899            return mSettings.getInstallerPackageNameLPr(packageName);
17900        }
17901    }
17902
17903    public boolean isOrphaned(String packageName) {
17904        // reader
17905        synchronized (mPackages) {
17906            return mSettings.isOrphaned(packageName);
17907        }
17908    }
17909
17910    @Override
17911    public int getApplicationEnabledSetting(String packageName, int userId) {
17912        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17913        int uid = Binder.getCallingUid();
17914        enforceCrossUserPermission(uid, userId,
17915                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17916        // reader
17917        synchronized (mPackages) {
17918            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17919        }
17920    }
17921
17922    @Override
17923    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17924        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17925        int uid = Binder.getCallingUid();
17926        enforceCrossUserPermission(uid, userId,
17927                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17928        // reader
17929        synchronized (mPackages) {
17930            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17931        }
17932    }
17933
17934    @Override
17935    public void enterSafeMode() {
17936        enforceSystemOrRoot("Only the system can request entering safe mode");
17937
17938        if (!mSystemReady) {
17939            mSafeMode = true;
17940        }
17941    }
17942
17943    @Override
17944    public void systemReady() {
17945        mSystemReady = true;
17946
17947        // Read the compatibilty setting when the system is ready.
17948        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17949                mContext.getContentResolver(),
17950                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17951        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17952        if (DEBUG_SETTINGS) {
17953            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17954        }
17955
17956        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17957
17958        synchronized (mPackages) {
17959            // Verify that all of the preferred activity components actually
17960            // exist.  It is possible for applications to be updated and at
17961            // that point remove a previously declared activity component that
17962            // had been set as a preferred activity.  We try to clean this up
17963            // the next time we encounter that preferred activity, but it is
17964            // possible for the user flow to never be able to return to that
17965            // situation so here we do a sanity check to make sure we haven't
17966            // left any junk around.
17967            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17968            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17969                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17970                removed.clear();
17971                for (PreferredActivity pa : pir.filterSet()) {
17972                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17973                        removed.add(pa);
17974                    }
17975                }
17976                if (removed.size() > 0) {
17977                    for (int r=0; r<removed.size(); r++) {
17978                        PreferredActivity pa = removed.get(r);
17979                        Slog.w(TAG, "Removing dangling preferred activity: "
17980                                + pa.mPref.mComponent);
17981                        pir.removeFilter(pa);
17982                    }
17983                    mSettings.writePackageRestrictionsLPr(
17984                            mSettings.mPreferredActivities.keyAt(i));
17985                }
17986            }
17987
17988            for (int userId : UserManagerService.getInstance().getUserIds()) {
17989                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17990                    grantPermissionsUserIds = ArrayUtils.appendInt(
17991                            grantPermissionsUserIds, userId);
17992                }
17993            }
17994        }
17995        sUserManager.systemReady();
17996
17997        // If we upgraded grant all default permissions before kicking off.
17998        for (int userId : grantPermissionsUserIds) {
17999            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
18000        }
18001
18002        // Kick off any messages waiting for system ready
18003        if (mPostSystemReadyMessages != null) {
18004            for (Message msg : mPostSystemReadyMessages) {
18005                msg.sendToTarget();
18006            }
18007            mPostSystemReadyMessages = null;
18008        }
18009
18010        // Watch for external volumes that come and go over time
18011        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18012        storage.registerListener(mStorageListener);
18013
18014        mInstallerService.systemReady();
18015        mPackageDexOptimizer.systemReady();
18016
18017        MountServiceInternal mountServiceInternal = LocalServices.getService(
18018                MountServiceInternal.class);
18019        mountServiceInternal.addExternalStoragePolicy(
18020                new MountServiceInternal.ExternalStorageMountPolicy() {
18021            @Override
18022            public int getMountMode(int uid, String packageName) {
18023                if (Process.isIsolated(uid)) {
18024                    return Zygote.MOUNT_EXTERNAL_NONE;
18025                }
18026                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
18027                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18028                }
18029                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18030                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
18031                }
18032                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
18033                    return Zygote.MOUNT_EXTERNAL_READ;
18034                }
18035                return Zygote.MOUNT_EXTERNAL_WRITE;
18036            }
18037
18038            @Override
18039            public boolean hasExternalStorage(int uid, String packageName) {
18040                return true;
18041            }
18042        });
18043
18044        // Now that we're mostly running, clean up stale users and apps
18045        reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
18046        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
18047    }
18048
18049    @Override
18050    public boolean isSafeMode() {
18051        return mSafeMode;
18052    }
18053
18054    @Override
18055    public boolean hasSystemUidErrors() {
18056        return mHasSystemUidErrors;
18057    }
18058
18059    static String arrayToString(int[] array) {
18060        StringBuffer buf = new StringBuffer(128);
18061        buf.append('[');
18062        if (array != null) {
18063            for (int i=0; i<array.length; i++) {
18064                if (i > 0) buf.append(", ");
18065                buf.append(array[i]);
18066            }
18067        }
18068        buf.append(']');
18069        return buf.toString();
18070    }
18071
18072    static class DumpState {
18073        public static final int DUMP_LIBS = 1 << 0;
18074        public static final int DUMP_FEATURES = 1 << 1;
18075        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
18076        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
18077        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
18078        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
18079        public static final int DUMP_PERMISSIONS = 1 << 6;
18080        public static final int DUMP_PACKAGES = 1 << 7;
18081        public static final int DUMP_SHARED_USERS = 1 << 8;
18082        public static final int DUMP_MESSAGES = 1 << 9;
18083        public static final int DUMP_PROVIDERS = 1 << 10;
18084        public static final int DUMP_VERIFIERS = 1 << 11;
18085        public static final int DUMP_PREFERRED = 1 << 12;
18086        public static final int DUMP_PREFERRED_XML = 1 << 13;
18087        public static final int DUMP_KEYSETS = 1 << 14;
18088        public static final int DUMP_VERSION = 1 << 15;
18089        public static final int DUMP_INSTALLS = 1 << 16;
18090        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
18091        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
18092        public static final int DUMP_FROZEN = 1 << 19;
18093        public static final int DUMP_DEXOPT = 1 << 20;
18094
18095        public static final int OPTION_SHOW_FILTERS = 1 << 0;
18096
18097        private int mTypes;
18098
18099        private int mOptions;
18100
18101        private boolean mTitlePrinted;
18102
18103        private SharedUserSetting mSharedUser;
18104
18105        public boolean isDumping(int type) {
18106            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
18107                return true;
18108            }
18109
18110            return (mTypes & type) != 0;
18111        }
18112
18113        public void setDump(int type) {
18114            mTypes |= type;
18115        }
18116
18117        public boolean isOptionEnabled(int option) {
18118            return (mOptions & option) != 0;
18119        }
18120
18121        public void setOptionEnabled(int option) {
18122            mOptions |= option;
18123        }
18124
18125        public boolean onTitlePrinted() {
18126            final boolean printed = mTitlePrinted;
18127            mTitlePrinted = true;
18128            return printed;
18129        }
18130
18131        public boolean getTitlePrinted() {
18132            return mTitlePrinted;
18133        }
18134
18135        public void setTitlePrinted(boolean enabled) {
18136            mTitlePrinted = enabled;
18137        }
18138
18139        public SharedUserSetting getSharedUser() {
18140            return mSharedUser;
18141        }
18142
18143        public void setSharedUser(SharedUserSetting user) {
18144            mSharedUser = user;
18145        }
18146    }
18147
18148    @Override
18149    public void onShellCommand(FileDescriptor in, FileDescriptor out,
18150            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
18151        (new PackageManagerShellCommand(this)).exec(
18152                this, in, out, err, args, resultReceiver);
18153    }
18154
18155    @Override
18156    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
18157        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
18158                != PackageManager.PERMISSION_GRANTED) {
18159            pw.println("Permission Denial: can't dump ActivityManager from from pid="
18160                    + Binder.getCallingPid()
18161                    + ", uid=" + Binder.getCallingUid()
18162                    + " without permission "
18163                    + android.Manifest.permission.DUMP);
18164            return;
18165        }
18166
18167        DumpState dumpState = new DumpState();
18168        boolean fullPreferred = false;
18169        boolean checkin = false;
18170
18171        String packageName = null;
18172        ArraySet<String> permissionNames = null;
18173
18174        int opti = 0;
18175        while (opti < args.length) {
18176            String opt = args[opti];
18177            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
18178                break;
18179            }
18180            opti++;
18181
18182            if ("-a".equals(opt)) {
18183                // Right now we only know how to print all.
18184            } else if ("-h".equals(opt)) {
18185                pw.println("Package manager dump options:");
18186                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
18187                pw.println("    --checkin: dump for a checkin");
18188                pw.println("    -f: print details of intent filters");
18189                pw.println("    -h: print this help");
18190                pw.println("  cmd may be one of:");
18191                pw.println("    l[ibraries]: list known shared libraries");
18192                pw.println("    f[eatures]: list device features");
18193                pw.println("    k[eysets]: print known keysets");
18194                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
18195                pw.println("    perm[issions]: dump permissions");
18196                pw.println("    permission [name ...]: dump declaration and use of given permission");
18197                pw.println("    pref[erred]: print preferred package settings");
18198                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
18199                pw.println("    prov[iders]: dump content providers");
18200                pw.println("    p[ackages]: dump installed packages");
18201                pw.println("    s[hared-users]: dump shared user IDs");
18202                pw.println("    m[essages]: print collected runtime messages");
18203                pw.println("    v[erifiers]: print package verifier info");
18204                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
18205                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
18206                pw.println("    version: print database version info");
18207                pw.println("    write: write current settings now");
18208                pw.println("    installs: details about install sessions");
18209                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
18210                pw.println("    dexopt: dump dexopt state");
18211                pw.println("    <package.name>: info about given package");
18212                return;
18213            } else if ("--checkin".equals(opt)) {
18214                checkin = true;
18215            } else if ("-f".equals(opt)) {
18216                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18217            } else {
18218                pw.println("Unknown argument: " + opt + "; use -h for help");
18219            }
18220        }
18221
18222        // Is the caller requesting to dump a particular piece of data?
18223        if (opti < args.length) {
18224            String cmd = args[opti];
18225            opti++;
18226            // Is this a package name?
18227            if ("android".equals(cmd) || cmd.contains(".")) {
18228                packageName = cmd;
18229                // When dumping a single package, we always dump all of its
18230                // filter information since the amount of data will be reasonable.
18231                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
18232            } else if ("check-permission".equals(cmd)) {
18233                if (opti >= args.length) {
18234                    pw.println("Error: check-permission missing permission argument");
18235                    return;
18236                }
18237                String perm = args[opti];
18238                opti++;
18239                if (opti >= args.length) {
18240                    pw.println("Error: check-permission missing package argument");
18241                    return;
18242                }
18243                String pkg = args[opti];
18244                opti++;
18245                int user = UserHandle.getUserId(Binder.getCallingUid());
18246                if (opti < args.length) {
18247                    try {
18248                        user = Integer.parseInt(args[opti]);
18249                    } catch (NumberFormatException e) {
18250                        pw.println("Error: check-permission user argument is not a number: "
18251                                + args[opti]);
18252                        return;
18253                    }
18254                }
18255                pw.println(checkPermission(perm, pkg, user));
18256                return;
18257            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
18258                dumpState.setDump(DumpState.DUMP_LIBS);
18259            } else if ("f".equals(cmd) || "features".equals(cmd)) {
18260                dumpState.setDump(DumpState.DUMP_FEATURES);
18261            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
18262                if (opti >= args.length) {
18263                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
18264                            | DumpState.DUMP_SERVICE_RESOLVERS
18265                            | DumpState.DUMP_RECEIVER_RESOLVERS
18266                            | DumpState.DUMP_CONTENT_RESOLVERS);
18267                } else {
18268                    while (opti < args.length) {
18269                        String name = args[opti];
18270                        if ("a".equals(name) || "activity".equals(name)) {
18271                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
18272                        } else if ("s".equals(name) || "service".equals(name)) {
18273                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
18274                        } else if ("r".equals(name) || "receiver".equals(name)) {
18275                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
18276                        } else if ("c".equals(name) || "content".equals(name)) {
18277                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
18278                        } else {
18279                            pw.println("Error: unknown resolver table type: " + name);
18280                            return;
18281                        }
18282                        opti++;
18283                    }
18284                }
18285            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
18286                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
18287            } else if ("permission".equals(cmd)) {
18288                if (opti >= args.length) {
18289                    pw.println("Error: permission requires permission name");
18290                    return;
18291                }
18292                permissionNames = new ArraySet<>();
18293                while (opti < args.length) {
18294                    permissionNames.add(args[opti]);
18295                    opti++;
18296                }
18297                dumpState.setDump(DumpState.DUMP_PERMISSIONS
18298                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
18299            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
18300                dumpState.setDump(DumpState.DUMP_PREFERRED);
18301            } else if ("preferred-xml".equals(cmd)) {
18302                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
18303                if (opti < args.length && "--full".equals(args[opti])) {
18304                    fullPreferred = true;
18305                    opti++;
18306                }
18307            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
18308                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
18309            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
18310                dumpState.setDump(DumpState.DUMP_PACKAGES);
18311            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
18312                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
18313            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
18314                dumpState.setDump(DumpState.DUMP_PROVIDERS);
18315            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
18316                dumpState.setDump(DumpState.DUMP_MESSAGES);
18317            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
18318                dumpState.setDump(DumpState.DUMP_VERIFIERS);
18319            } else if ("i".equals(cmd) || "ifv".equals(cmd)
18320                    || "intent-filter-verifiers".equals(cmd)) {
18321                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
18322            } else if ("version".equals(cmd)) {
18323                dumpState.setDump(DumpState.DUMP_VERSION);
18324            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
18325                dumpState.setDump(DumpState.DUMP_KEYSETS);
18326            } else if ("installs".equals(cmd)) {
18327                dumpState.setDump(DumpState.DUMP_INSTALLS);
18328            } else if ("frozen".equals(cmd)) {
18329                dumpState.setDump(DumpState.DUMP_FROZEN);
18330            } else if ("dexopt".equals(cmd)) {
18331                dumpState.setDump(DumpState.DUMP_DEXOPT);
18332            } else if ("write".equals(cmd)) {
18333                synchronized (mPackages) {
18334                    mSettings.writeLPr();
18335                    pw.println("Settings written.");
18336                    return;
18337                }
18338            }
18339        }
18340
18341        if (checkin) {
18342            pw.println("vers,1");
18343        }
18344
18345        // reader
18346        synchronized (mPackages) {
18347            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
18348                if (!checkin) {
18349                    if (dumpState.onTitlePrinted())
18350                        pw.println();
18351                    pw.println("Database versions:");
18352                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
18353                }
18354            }
18355
18356            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
18357                if (!checkin) {
18358                    if (dumpState.onTitlePrinted())
18359                        pw.println();
18360                    pw.println("Verifiers:");
18361                    pw.print("  Required: ");
18362                    pw.print(mRequiredVerifierPackage);
18363                    pw.print(" (uid=");
18364                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18365                            UserHandle.USER_SYSTEM));
18366                    pw.println(")");
18367                } else if (mRequiredVerifierPackage != null) {
18368                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
18369                    pw.print(",");
18370                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
18371                            UserHandle.USER_SYSTEM));
18372                }
18373            }
18374
18375            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
18376                    packageName == null) {
18377                if (mIntentFilterVerifierComponent != null) {
18378                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
18379                    if (!checkin) {
18380                        if (dumpState.onTitlePrinted())
18381                            pw.println();
18382                        pw.println("Intent Filter Verifier:");
18383                        pw.print("  Using: ");
18384                        pw.print(verifierPackageName);
18385                        pw.print(" (uid=");
18386                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18387                                UserHandle.USER_SYSTEM));
18388                        pw.println(")");
18389                    } else if (verifierPackageName != null) {
18390                        pw.print("ifv,"); pw.print(verifierPackageName);
18391                        pw.print(",");
18392                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
18393                                UserHandle.USER_SYSTEM));
18394                    }
18395                } else {
18396                    pw.println();
18397                    pw.println("No Intent Filter Verifier available!");
18398                }
18399            }
18400
18401            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
18402                boolean printedHeader = false;
18403                final Iterator<String> it = mSharedLibraries.keySet().iterator();
18404                while (it.hasNext()) {
18405                    String name = it.next();
18406                    SharedLibraryEntry ent = mSharedLibraries.get(name);
18407                    if (!checkin) {
18408                        if (!printedHeader) {
18409                            if (dumpState.onTitlePrinted())
18410                                pw.println();
18411                            pw.println("Libraries:");
18412                            printedHeader = true;
18413                        }
18414                        pw.print("  ");
18415                    } else {
18416                        pw.print("lib,");
18417                    }
18418                    pw.print(name);
18419                    if (!checkin) {
18420                        pw.print(" -> ");
18421                    }
18422                    if (ent.path != null) {
18423                        if (!checkin) {
18424                            pw.print("(jar) ");
18425                            pw.print(ent.path);
18426                        } else {
18427                            pw.print(",jar,");
18428                            pw.print(ent.path);
18429                        }
18430                    } else {
18431                        if (!checkin) {
18432                            pw.print("(apk) ");
18433                            pw.print(ent.apk);
18434                        } else {
18435                            pw.print(",apk,");
18436                            pw.print(ent.apk);
18437                        }
18438                    }
18439                    pw.println();
18440                }
18441            }
18442
18443            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
18444                if (dumpState.onTitlePrinted())
18445                    pw.println();
18446                if (!checkin) {
18447                    pw.println("Features:");
18448                }
18449
18450                for (FeatureInfo feat : mAvailableFeatures.values()) {
18451                    if (checkin) {
18452                        pw.print("feat,");
18453                        pw.print(feat.name);
18454                        pw.print(",");
18455                        pw.println(feat.version);
18456                    } else {
18457                        pw.print("  ");
18458                        pw.print(feat.name);
18459                        if (feat.version > 0) {
18460                            pw.print(" version=");
18461                            pw.print(feat.version);
18462                        }
18463                        pw.println();
18464                    }
18465                }
18466            }
18467
18468            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
18469                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
18470                        : "Activity Resolver Table:", "  ", packageName,
18471                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18472                    dumpState.setTitlePrinted(true);
18473                }
18474            }
18475            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
18476                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
18477                        : "Receiver Resolver Table:", "  ", packageName,
18478                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18479                    dumpState.setTitlePrinted(true);
18480                }
18481            }
18482            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
18483                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
18484                        : "Service Resolver Table:", "  ", packageName,
18485                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18486                    dumpState.setTitlePrinted(true);
18487                }
18488            }
18489            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
18490                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
18491                        : "Provider Resolver Table:", "  ", packageName,
18492                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
18493                    dumpState.setTitlePrinted(true);
18494                }
18495            }
18496
18497            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
18498                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
18499                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
18500                    int user = mSettings.mPreferredActivities.keyAt(i);
18501                    if (pir.dump(pw,
18502                            dumpState.getTitlePrinted()
18503                                ? "\nPreferred Activities User " + user + ":"
18504                                : "Preferred Activities User " + user + ":", "  ",
18505                            packageName, true, false)) {
18506                        dumpState.setTitlePrinted(true);
18507                    }
18508                }
18509            }
18510
18511            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
18512                pw.flush();
18513                FileOutputStream fout = new FileOutputStream(fd);
18514                BufferedOutputStream str = new BufferedOutputStream(fout);
18515                XmlSerializer serializer = new FastXmlSerializer();
18516                try {
18517                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
18518                    serializer.startDocument(null, true);
18519                    serializer.setFeature(
18520                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
18521                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
18522                    serializer.endDocument();
18523                    serializer.flush();
18524                } catch (IllegalArgumentException e) {
18525                    pw.println("Failed writing: " + e);
18526                } catch (IllegalStateException e) {
18527                    pw.println("Failed writing: " + e);
18528                } catch (IOException e) {
18529                    pw.println("Failed writing: " + e);
18530                }
18531            }
18532
18533            if (!checkin
18534                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
18535                    && packageName == null) {
18536                pw.println();
18537                int count = mSettings.mPackages.size();
18538                if (count == 0) {
18539                    pw.println("No applications!");
18540                    pw.println();
18541                } else {
18542                    final String prefix = "  ";
18543                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
18544                    if (allPackageSettings.size() == 0) {
18545                        pw.println("No domain preferred apps!");
18546                        pw.println();
18547                    } else {
18548                        pw.println("App verification status:");
18549                        pw.println();
18550                        count = 0;
18551                        for (PackageSetting ps : allPackageSettings) {
18552                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
18553                            if (ivi == null || ivi.getPackageName() == null) continue;
18554                            pw.println(prefix + "Package: " + ivi.getPackageName());
18555                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
18556                            pw.println(prefix + "Status:  " + ivi.getStatusString());
18557                            pw.println();
18558                            count++;
18559                        }
18560                        if (count == 0) {
18561                            pw.println(prefix + "No app verification established.");
18562                            pw.println();
18563                        }
18564                        for (int userId : sUserManager.getUserIds()) {
18565                            pw.println("App linkages for user " + userId + ":");
18566                            pw.println();
18567                            count = 0;
18568                            for (PackageSetting ps : allPackageSettings) {
18569                                final long status = ps.getDomainVerificationStatusForUser(userId);
18570                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
18571                                    continue;
18572                                }
18573                                pw.println(prefix + "Package: " + ps.name);
18574                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
18575                                String statusStr = IntentFilterVerificationInfo.
18576                                        getStatusStringFromValue(status);
18577                                pw.println(prefix + "Status:  " + statusStr);
18578                                pw.println();
18579                                count++;
18580                            }
18581                            if (count == 0) {
18582                                pw.println(prefix + "No configured app linkages.");
18583                                pw.println();
18584                            }
18585                        }
18586                    }
18587                }
18588            }
18589
18590            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
18591                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
18592                if (packageName == null && permissionNames == null) {
18593                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
18594                        if (iperm == 0) {
18595                            if (dumpState.onTitlePrinted())
18596                                pw.println();
18597                            pw.println("AppOp Permissions:");
18598                        }
18599                        pw.print("  AppOp Permission ");
18600                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
18601                        pw.println(":");
18602                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
18603                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
18604                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
18605                        }
18606                    }
18607                }
18608            }
18609
18610            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
18611                boolean printedSomething = false;
18612                for (PackageParser.Provider p : mProviders.mProviders.values()) {
18613                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18614                        continue;
18615                    }
18616                    if (!printedSomething) {
18617                        if (dumpState.onTitlePrinted())
18618                            pw.println();
18619                        pw.println("Registered ContentProviders:");
18620                        printedSomething = true;
18621                    }
18622                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
18623                    pw.print("    "); pw.println(p.toString());
18624                }
18625                printedSomething = false;
18626                for (Map.Entry<String, PackageParser.Provider> entry :
18627                        mProvidersByAuthority.entrySet()) {
18628                    PackageParser.Provider p = entry.getValue();
18629                    if (packageName != null && !packageName.equals(p.info.packageName)) {
18630                        continue;
18631                    }
18632                    if (!printedSomething) {
18633                        if (dumpState.onTitlePrinted())
18634                            pw.println();
18635                        pw.println("ContentProvider Authorities:");
18636                        printedSomething = true;
18637                    }
18638                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
18639                    pw.print("    "); pw.println(p.toString());
18640                    if (p.info != null && p.info.applicationInfo != null) {
18641                        final String appInfo = p.info.applicationInfo.toString();
18642                        pw.print("      applicationInfo="); pw.println(appInfo);
18643                    }
18644                }
18645            }
18646
18647            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
18648                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
18649            }
18650
18651            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
18652                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
18653            }
18654
18655            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
18656                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
18657            }
18658
18659            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
18660                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
18661            }
18662
18663            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
18664                // XXX should handle packageName != null by dumping only install data that
18665                // the given package is involved with.
18666                if (dumpState.onTitlePrinted()) pw.println();
18667                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
18668            }
18669
18670            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
18671                // XXX should handle packageName != null by dumping only install data that
18672                // the given package is involved with.
18673                if (dumpState.onTitlePrinted()) pw.println();
18674
18675                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18676                ipw.println();
18677                ipw.println("Frozen packages:");
18678                ipw.increaseIndent();
18679                if (mFrozenPackages.size() == 0) {
18680                    ipw.println("(none)");
18681                } else {
18682                    for (int i = 0; i < mFrozenPackages.size(); i++) {
18683                        ipw.println(mFrozenPackages.valueAt(i));
18684                    }
18685                }
18686                ipw.decreaseIndent();
18687            }
18688
18689            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
18690                if (dumpState.onTitlePrinted()) pw.println();
18691                dumpDexoptStateLPr(pw, packageName);
18692            }
18693
18694            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
18695                if (dumpState.onTitlePrinted()) pw.println();
18696                mSettings.dumpReadMessagesLPr(pw, dumpState);
18697
18698                pw.println();
18699                pw.println("Package warning messages:");
18700                BufferedReader in = null;
18701                String line = null;
18702                try {
18703                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18704                    while ((line = in.readLine()) != null) {
18705                        if (line.contains("ignored: updated version")) continue;
18706                        pw.println(line);
18707                    }
18708                } catch (IOException ignored) {
18709                } finally {
18710                    IoUtils.closeQuietly(in);
18711                }
18712            }
18713
18714            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
18715                BufferedReader in = null;
18716                String line = null;
18717                try {
18718                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
18719                    while ((line = in.readLine()) != null) {
18720                        if (line.contains("ignored: updated version")) continue;
18721                        pw.print("msg,");
18722                        pw.println(line);
18723                    }
18724                } catch (IOException ignored) {
18725                } finally {
18726                    IoUtils.closeQuietly(in);
18727                }
18728            }
18729        }
18730    }
18731
18732    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
18733        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
18734        ipw.println();
18735        ipw.println("Dexopt state:");
18736        ipw.increaseIndent();
18737        Collection<PackageParser.Package> packages = null;
18738        if (packageName != null) {
18739            PackageParser.Package targetPackage = mPackages.get(packageName);
18740            if (targetPackage != null) {
18741                packages = Collections.singletonList(targetPackage);
18742            } else {
18743                ipw.println("Unable to find package: " + packageName);
18744                return;
18745            }
18746        } else {
18747            packages = mPackages.values();
18748        }
18749
18750        for (PackageParser.Package pkg : packages) {
18751            ipw.println("[" + pkg.packageName + "]");
18752            ipw.increaseIndent();
18753            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
18754            ipw.decreaseIndent();
18755        }
18756    }
18757
18758    private String dumpDomainString(String packageName) {
18759        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18760                .getList();
18761        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18762
18763        ArraySet<String> result = new ArraySet<>();
18764        if (iviList.size() > 0) {
18765            for (IntentFilterVerificationInfo ivi : iviList) {
18766                for (String host : ivi.getDomains()) {
18767                    result.add(host);
18768                }
18769            }
18770        }
18771        if (filters != null && filters.size() > 0) {
18772            for (IntentFilter filter : filters) {
18773                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18774                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18775                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18776                    result.addAll(filter.getHostsList());
18777                }
18778            }
18779        }
18780
18781        StringBuilder sb = new StringBuilder(result.size() * 16);
18782        for (String domain : result) {
18783            if (sb.length() > 0) sb.append(" ");
18784            sb.append(domain);
18785        }
18786        return sb.toString();
18787    }
18788
18789    // ------- apps on sdcard specific code -------
18790    static final boolean DEBUG_SD_INSTALL = false;
18791
18792    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18793
18794    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18795
18796    private boolean mMediaMounted = false;
18797
18798    static String getEncryptKey() {
18799        try {
18800            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18801                    SD_ENCRYPTION_KEYSTORE_NAME);
18802            if (sdEncKey == null) {
18803                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18804                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18805                if (sdEncKey == null) {
18806                    Slog.e(TAG, "Failed to create encryption keys");
18807                    return null;
18808                }
18809            }
18810            return sdEncKey;
18811        } catch (NoSuchAlgorithmException nsae) {
18812            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18813            return null;
18814        } catch (IOException ioe) {
18815            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18816            return null;
18817        }
18818    }
18819
18820    /*
18821     * Update media status on PackageManager.
18822     */
18823    @Override
18824    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18825        int callingUid = Binder.getCallingUid();
18826        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18827            throw new SecurityException("Media status can only be updated by the system");
18828        }
18829        // reader; this apparently protects mMediaMounted, but should probably
18830        // be a different lock in that case.
18831        synchronized (mPackages) {
18832            Log.i(TAG, "Updating external media status from "
18833                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18834                    + (mediaStatus ? "mounted" : "unmounted"));
18835            if (DEBUG_SD_INSTALL)
18836                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18837                        + ", mMediaMounted=" + mMediaMounted);
18838            if (mediaStatus == mMediaMounted) {
18839                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18840                        : 0, -1);
18841                mHandler.sendMessage(msg);
18842                return;
18843            }
18844            mMediaMounted = mediaStatus;
18845        }
18846        // Queue up an async operation since the package installation may take a
18847        // little while.
18848        mHandler.post(new Runnable() {
18849            public void run() {
18850                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18851            }
18852        });
18853    }
18854
18855    /**
18856     * Called by MountService when the initial ASECs to scan are available.
18857     * Should block until all the ASEC containers are finished being scanned.
18858     */
18859    public void scanAvailableAsecs() {
18860        updateExternalMediaStatusInner(true, false, false);
18861    }
18862
18863    /*
18864     * Collect information of applications on external media, map them against
18865     * existing containers and update information based on current mount status.
18866     * Please note that we always have to report status if reportStatus has been
18867     * set to true especially when unloading packages.
18868     */
18869    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18870            boolean externalStorage) {
18871        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18872        int[] uidArr = EmptyArray.INT;
18873
18874        final String[] list = PackageHelper.getSecureContainerList();
18875        if (ArrayUtils.isEmpty(list)) {
18876            Log.i(TAG, "No secure containers found");
18877        } else {
18878            // Process list of secure containers and categorize them
18879            // as active or stale based on their package internal state.
18880
18881            // reader
18882            synchronized (mPackages) {
18883                for (String cid : list) {
18884                    // Leave stages untouched for now; installer service owns them
18885                    if (PackageInstallerService.isStageName(cid)) continue;
18886
18887                    if (DEBUG_SD_INSTALL)
18888                        Log.i(TAG, "Processing container " + cid);
18889                    String pkgName = getAsecPackageName(cid);
18890                    if (pkgName == null) {
18891                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18892                        continue;
18893                    }
18894                    if (DEBUG_SD_INSTALL)
18895                        Log.i(TAG, "Looking for pkg : " + pkgName);
18896
18897                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18898                    if (ps == null) {
18899                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18900                        continue;
18901                    }
18902
18903                    /*
18904                     * Skip packages that are not external if we're unmounting
18905                     * external storage.
18906                     */
18907                    if (externalStorage && !isMounted && !isExternal(ps)) {
18908                        continue;
18909                    }
18910
18911                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18912                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18913                    // The package status is changed only if the code path
18914                    // matches between settings and the container id.
18915                    if (ps.codePathString != null
18916                            && ps.codePathString.startsWith(args.getCodePath())) {
18917                        if (DEBUG_SD_INSTALL) {
18918                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18919                                    + " at code path: " + ps.codePathString);
18920                        }
18921
18922                        // We do have a valid package installed on sdcard
18923                        processCids.put(args, ps.codePathString);
18924                        final int uid = ps.appId;
18925                        if (uid != -1) {
18926                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18927                        }
18928                    } else {
18929                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18930                                + ps.codePathString);
18931                    }
18932                }
18933            }
18934
18935            Arrays.sort(uidArr);
18936        }
18937
18938        // Process packages with valid entries.
18939        if (isMounted) {
18940            if (DEBUG_SD_INSTALL)
18941                Log.i(TAG, "Loading packages");
18942            loadMediaPackages(processCids, uidArr, externalStorage);
18943            startCleaningPackages();
18944            mInstallerService.onSecureContainersAvailable();
18945        } else {
18946            if (DEBUG_SD_INSTALL)
18947                Log.i(TAG, "Unloading packages");
18948            unloadMediaPackages(processCids, uidArr, reportStatus);
18949        }
18950    }
18951
18952    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18953            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18954        final int size = infos.size();
18955        final String[] packageNames = new String[size];
18956        final int[] packageUids = new int[size];
18957        for (int i = 0; i < size; i++) {
18958            final ApplicationInfo info = infos.get(i);
18959            packageNames[i] = info.packageName;
18960            packageUids[i] = info.uid;
18961        }
18962        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18963                finishedReceiver);
18964    }
18965
18966    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18967            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18968        sendResourcesChangedBroadcast(mediaStatus, replacing,
18969                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18970    }
18971
18972    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18973            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18974        int size = pkgList.length;
18975        if (size > 0) {
18976            // Send broadcasts here
18977            Bundle extras = new Bundle();
18978            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18979            if (uidArr != null) {
18980                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18981            }
18982            if (replacing) {
18983                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18984            }
18985            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18986                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18987            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18988        }
18989    }
18990
18991   /*
18992     * Look at potentially valid container ids from processCids If package
18993     * information doesn't match the one on record or package scanning fails,
18994     * the cid is added to list of removeCids. We currently don't delete stale
18995     * containers.
18996     */
18997    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18998            boolean externalStorage) {
18999        ArrayList<String> pkgList = new ArrayList<String>();
19000        Set<AsecInstallArgs> keys = processCids.keySet();
19001
19002        for (AsecInstallArgs args : keys) {
19003            String codePath = processCids.get(args);
19004            if (DEBUG_SD_INSTALL)
19005                Log.i(TAG, "Loading container : " + args.cid);
19006            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
19007            try {
19008                // Make sure there are no container errors first.
19009                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
19010                    Slog.e(TAG, "Failed to mount cid : " + args.cid
19011                            + " when installing from sdcard");
19012                    continue;
19013                }
19014                // Check code path here.
19015                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
19016                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
19017                            + " does not match one in settings " + codePath);
19018                    continue;
19019                }
19020                // Parse package
19021                int parseFlags = mDefParseFlags;
19022                if (args.isExternalAsec()) {
19023                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
19024                }
19025                if (args.isFwdLocked()) {
19026                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
19027                }
19028
19029                synchronized (mInstallLock) {
19030                    PackageParser.Package pkg = null;
19031                    try {
19032                        // Sadly we don't know the package name yet to freeze it
19033                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
19034                                SCAN_IGNORE_FROZEN, 0, null);
19035                    } catch (PackageManagerException e) {
19036                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
19037                    }
19038                    // Scan the package
19039                    if (pkg != null) {
19040                        /*
19041                         * TODO why is the lock being held? doPostInstall is
19042                         * called in other places without the lock. This needs
19043                         * to be straightened out.
19044                         */
19045                        // writer
19046                        synchronized (mPackages) {
19047                            retCode = PackageManager.INSTALL_SUCCEEDED;
19048                            pkgList.add(pkg.packageName);
19049                            // Post process args
19050                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
19051                                    pkg.applicationInfo.uid);
19052                        }
19053                    } else {
19054                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
19055                    }
19056                }
19057
19058            } finally {
19059                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
19060                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
19061                }
19062            }
19063        }
19064        // writer
19065        synchronized (mPackages) {
19066            // If the platform SDK has changed since the last time we booted,
19067            // we need to re-grant app permission to catch any new ones that
19068            // appear. This is really a hack, and means that apps can in some
19069            // cases get permissions that the user didn't initially explicitly
19070            // allow... it would be nice to have some better way to handle
19071            // this situation.
19072            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
19073                    : mSettings.getInternalVersion();
19074            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
19075                    : StorageManager.UUID_PRIVATE_INTERNAL;
19076
19077            int updateFlags = UPDATE_PERMISSIONS_ALL;
19078            if (ver.sdkVersion != mSdkVersion) {
19079                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19080                        + mSdkVersion + "; regranting permissions for external");
19081                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19082            }
19083            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19084
19085            // Yay, everything is now upgraded
19086            ver.forceCurrent();
19087
19088            // can downgrade to reader
19089            // Persist settings
19090            mSettings.writeLPr();
19091        }
19092        // Send a broadcast to let everyone know we are done processing
19093        if (pkgList.size() > 0) {
19094            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
19095        }
19096    }
19097
19098   /*
19099     * Utility method to unload a list of specified containers
19100     */
19101    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
19102        // Just unmount all valid containers.
19103        for (AsecInstallArgs arg : cidArgs) {
19104            synchronized (mInstallLock) {
19105                arg.doPostDeleteLI(false);
19106           }
19107       }
19108   }
19109
19110    /*
19111     * Unload packages mounted on external media. This involves deleting package
19112     * data from internal structures, sending broadcasts about disabled packages,
19113     * gc'ing to free up references, unmounting all secure containers
19114     * corresponding to packages on external media, and posting a
19115     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
19116     * that we always have to post this message if status has been requested no
19117     * matter what.
19118     */
19119    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
19120            final boolean reportStatus) {
19121        if (DEBUG_SD_INSTALL)
19122            Log.i(TAG, "unloading media packages");
19123        ArrayList<String> pkgList = new ArrayList<String>();
19124        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
19125        final Set<AsecInstallArgs> keys = processCids.keySet();
19126        for (AsecInstallArgs args : keys) {
19127            String pkgName = args.getPackageName();
19128            if (DEBUG_SD_INSTALL)
19129                Log.i(TAG, "Trying to unload pkg : " + pkgName);
19130            // Delete package internally
19131            PackageRemovedInfo outInfo = new PackageRemovedInfo();
19132            synchronized (mInstallLock) {
19133                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19134                final boolean res;
19135                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
19136                        "unloadMediaPackages")) {
19137                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
19138                            null);
19139                }
19140                if (res) {
19141                    pkgList.add(pkgName);
19142                } else {
19143                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
19144                    failedList.add(args);
19145                }
19146            }
19147        }
19148
19149        // reader
19150        synchronized (mPackages) {
19151            // We didn't update the settings after removing each package;
19152            // write them now for all packages.
19153            mSettings.writeLPr();
19154        }
19155
19156        // We have to absolutely send UPDATED_MEDIA_STATUS only
19157        // after confirming that all the receivers processed the ordered
19158        // broadcast when packages get disabled, force a gc to clean things up.
19159        // and unload all the containers.
19160        if (pkgList.size() > 0) {
19161            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
19162                    new IIntentReceiver.Stub() {
19163                public void performReceive(Intent intent, int resultCode, String data,
19164                        Bundle extras, boolean ordered, boolean sticky,
19165                        int sendingUser) throws RemoteException {
19166                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
19167                            reportStatus ? 1 : 0, 1, keys);
19168                    mHandler.sendMessage(msg);
19169                }
19170            });
19171        } else {
19172            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
19173                    keys);
19174            mHandler.sendMessage(msg);
19175        }
19176    }
19177
19178    private void loadPrivatePackages(final VolumeInfo vol) {
19179        mHandler.post(new Runnable() {
19180            @Override
19181            public void run() {
19182                loadPrivatePackagesInner(vol);
19183            }
19184        });
19185    }
19186
19187    private void loadPrivatePackagesInner(VolumeInfo vol) {
19188        final String volumeUuid = vol.fsUuid;
19189        if (TextUtils.isEmpty(volumeUuid)) {
19190            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
19191            return;
19192        }
19193
19194        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
19195        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
19196        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
19197
19198        final VersionInfo ver;
19199        final List<PackageSetting> packages;
19200        synchronized (mPackages) {
19201            ver = mSettings.findOrCreateVersion(volumeUuid);
19202            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19203        }
19204
19205        for (PackageSetting ps : packages) {
19206            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
19207            synchronized (mInstallLock) {
19208                final PackageParser.Package pkg;
19209                try {
19210                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
19211                    loaded.add(pkg.applicationInfo);
19212
19213                } catch (PackageManagerException e) {
19214                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
19215                }
19216
19217                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
19218                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
19219                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
19220                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19221                }
19222            }
19223        }
19224
19225        // Reconcile app data for all started/unlocked users
19226        final StorageManager sm = mContext.getSystemService(StorageManager.class);
19227        final UserManager um = mContext.getSystemService(UserManager.class);
19228        UserManagerInternal umInternal = getUserManagerInternal();
19229        for (UserInfo user : um.getUsers()) {
19230            final int flags;
19231            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19232                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19233            } else if (umInternal.isUserRunning(user.id)) {
19234                flags = StorageManager.FLAG_STORAGE_DE;
19235            } else {
19236                continue;
19237            }
19238
19239            try {
19240                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
19241                synchronized (mInstallLock) {
19242                    reconcileAppsDataLI(volumeUuid, user.id, flags);
19243                }
19244            } catch (IllegalStateException e) {
19245                // Device was probably ejected, and we'll process that event momentarily
19246                Slog.w(TAG, "Failed to prepare storage: " + e);
19247            }
19248        }
19249
19250        synchronized (mPackages) {
19251            int updateFlags = UPDATE_PERMISSIONS_ALL;
19252            if (ver.sdkVersion != mSdkVersion) {
19253                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
19254                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
19255                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
19256            }
19257            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
19258
19259            // Yay, everything is now upgraded
19260            ver.forceCurrent();
19261
19262            mSettings.writeLPr();
19263        }
19264
19265        for (PackageFreezer freezer : freezers) {
19266            freezer.close();
19267        }
19268
19269        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
19270        sendResourcesChangedBroadcast(true, false, loaded, null);
19271    }
19272
19273    private void unloadPrivatePackages(final VolumeInfo vol) {
19274        mHandler.post(new Runnable() {
19275            @Override
19276            public void run() {
19277                unloadPrivatePackagesInner(vol);
19278            }
19279        });
19280    }
19281
19282    private void unloadPrivatePackagesInner(VolumeInfo vol) {
19283        final String volumeUuid = vol.fsUuid;
19284        if (TextUtils.isEmpty(volumeUuid)) {
19285            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
19286            return;
19287        }
19288
19289        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
19290        synchronized (mInstallLock) {
19291        synchronized (mPackages) {
19292            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
19293            for (PackageSetting ps : packages) {
19294                if (ps.pkg == null) continue;
19295
19296                final ApplicationInfo info = ps.pkg.applicationInfo;
19297                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
19298                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
19299
19300                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
19301                        "unloadPrivatePackagesInner")) {
19302                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
19303                            false, null)) {
19304                        unloaded.add(info);
19305                    } else {
19306                        Slog.w(TAG, "Failed to unload " + ps.codePath);
19307                    }
19308                }
19309
19310                // Try very hard to release any references to this package
19311                // so we don't risk the system server being killed due to
19312                // open FDs
19313                AttributeCache.instance().removePackage(ps.name);
19314            }
19315
19316            mSettings.writeLPr();
19317        }
19318        }
19319
19320        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
19321        sendResourcesChangedBroadcast(false, false, unloaded, null);
19322
19323        // Try very hard to release any references to this path so we don't risk
19324        // the system server being killed due to open FDs
19325        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
19326
19327        for (int i = 0; i < 3; i++) {
19328            System.gc();
19329            System.runFinalization();
19330        }
19331    }
19332
19333    /**
19334     * Prepare storage areas for given user on all mounted devices.
19335     */
19336    void prepareUserData(int userId, int userSerial, int flags) {
19337        synchronized (mInstallLock) {
19338            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19339            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19340                final String volumeUuid = vol.getFsUuid();
19341                prepareUserDataLI(volumeUuid, userId, userSerial, flags, true);
19342            }
19343        }
19344    }
19345
19346    private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags,
19347            boolean allowRecover) {
19348        // Prepare storage and verify that serial numbers are consistent; if
19349        // there's a mismatch we need to destroy to avoid leaking data
19350        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19351        try {
19352            storage.prepareUserStorage(volumeUuid, userId, userSerial, flags);
19353
19354            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) {
19355                UserManagerService.enforceSerialNumber(
19356                        Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial);
19357                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19358                    UserManagerService.enforceSerialNumber(
19359                            Environment.getDataSystemDeDirectory(userId), userSerial);
19360                }
19361            }
19362            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) {
19363                UserManagerService.enforceSerialNumber(
19364                        Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial);
19365                if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19366                    UserManagerService.enforceSerialNumber(
19367                            Environment.getDataSystemCeDirectory(userId), userSerial);
19368                }
19369            }
19370
19371            synchronized (mInstallLock) {
19372                mInstaller.createUserData(volumeUuid, userId, userSerial, flags);
19373            }
19374        } catch (Exception e) {
19375            logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid
19376                    + " because we failed to prepare: " + e);
19377            destroyUserDataLI(volumeUuid, userId,
19378                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19379
19380            if (allowRecover) {
19381                // Try one last time; if we fail again we're really in trouble
19382                prepareUserDataLI(volumeUuid, userId, userSerial, flags, false);
19383            }
19384        }
19385    }
19386
19387    /**
19388     * Destroy storage areas for given user on all mounted devices.
19389     */
19390    void destroyUserData(int userId, int flags) {
19391        synchronized (mInstallLock) {
19392            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19393            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19394                final String volumeUuid = vol.getFsUuid();
19395                destroyUserDataLI(volumeUuid, userId, flags);
19396            }
19397        }
19398    }
19399
19400    private void destroyUserDataLI(String volumeUuid, int userId, int flags) {
19401        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19402        try {
19403            // Clean up app data, profile data, and media data
19404            mInstaller.destroyUserData(volumeUuid, userId, flags);
19405
19406            // Clean up system data
19407            if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) {
19408                if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19409                    FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId));
19410                    FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId));
19411                }
19412                if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19413                    FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId));
19414                }
19415            }
19416
19417            // Data with special labels is now gone, so finish the job
19418            storage.destroyUserStorage(volumeUuid, userId, flags);
19419
19420        } catch (Exception e) {
19421            logCriticalInfo(Log.WARN,
19422                    "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e);
19423        }
19424    }
19425
19426    /**
19427     * Examine all users present on given mounted volume, and destroy data
19428     * belonging to users that are no longer valid, or whose user ID has been
19429     * recycled.
19430     */
19431    private void reconcileUsers(String volumeUuid) {
19432        final List<File> files = new ArrayList<>();
19433        Collections.addAll(files, FileUtils
19434                .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid)));
19435        Collections.addAll(files, FileUtils
19436                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)));
19437        Collections.addAll(files, FileUtils
19438                .listFilesOrEmpty(Environment.getDataSystemDeDirectory()));
19439        Collections.addAll(files, FileUtils
19440                .listFilesOrEmpty(Environment.getDataSystemCeDirectory()));
19441        for (File file : files) {
19442            if (!file.isDirectory()) continue;
19443
19444            final int userId;
19445            final UserInfo info;
19446            try {
19447                userId = Integer.parseInt(file.getName());
19448                info = sUserManager.getUserInfo(userId);
19449            } catch (NumberFormatException e) {
19450                Slog.w(TAG, "Invalid user directory " + file);
19451                continue;
19452            }
19453
19454            boolean destroyUser = false;
19455            if (info == null) {
19456                logCriticalInfo(Log.WARN, "Destroying user directory " + file
19457                        + " because no matching user was found");
19458                destroyUser = true;
19459            } else if (!mOnlyCore) {
19460                try {
19461                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
19462                } catch (IOException e) {
19463                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
19464                            + " because we failed to enforce serial number: " + e);
19465                    destroyUser = true;
19466                }
19467            }
19468
19469            if (destroyUser) {
19470                synchronized (mInstallLock) {
19471                    destroyUserDataLI(volumeUuid, userId,
19472                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19473                }
19474            }
19475        }
19476    }
19477
19478    private void assertPackageKnown(String volumeUuid, String packageName)
19479            throws PackageManagerException {
19480        synchronized (mPackages) {
19481            final PackageSetting ps = mSettings.mPackages.get(packageName);
19482            if (ps == null) {
19483                throw new PackageManagerException("Package " + packageName + " is unknown");
19484            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19485                throw new PackageManagerException(
19486                        "Package " + packageName + " found on unknown volume " + volumeUuid
19487                                + "; expected volume " + ps.volumeUuid);
19488            }
19489        }
19490    }
19491
19492    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
19493            throws PackageManagerException {
19494        synchronized (mPackages) {
19495            final PackageSetting ps = mSettings.mPackages.get(packageName);
19496            if (ps == null) {
19497                throw new PackageManagerException("Package " + packageName + " is unknown");
19498            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
19499                throw new PackageManagerException(
19500                        "Package " + packageName + " found on unknown volume " + volumeUuid
19501                                + "; expected volume " + ps.volumeUuid);
19502            } else if (!ps.getInstalled(userId)) {
19503                throw new PackageManagerException(
19504                        "Package " + packageName + " not installed for user " + userId);
19505            }
19506        }
19507    }
19508
19509    /**
19510     * Examine all apps present on given mounted volume, and destroy apps that
19511     * aren't expected, either due to uninstallation or reinstallation on
19512     * another volume.
19513     */
19514    private void reconcileApps(String volumeUuid) {
19515        final File[] files = FileUtils
19516                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
19517        for (File file : files) {
19518            final boolean isPackage = (isApkFile(file) || file.isDirectory())
19519                    && !PackageInstallerService.isStageName(file.getName());
19520            if (!isPackage) {
19521                // Ignore entries which are not packages
19522                continue;
19523            }
19524
19525            try {
19526                final PackageLite pkg = PackageParser.parsePackageLite(file,
19527                        PackageParser.PARSE_MUST_BE_APK);
19528                assertPackageKnown(volumeUuid, pkg.packageName);
19529
19530            } catch (PackageParserException | PackageManagerException e) {
19531                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19532                synchronized (mInstallLock) {
19533                    removeCodePathLI(file);
19534                }
19535            }
19536        }
19537    }
19538
19539    /**
19540     * Reconcile all app data for the given user.
19541     * <p>
19542     * Verifies that directories exist and that ownership and labeling is
19543     * correct for all installed apps on all mounted volumes.
19544     */
19545    void reconcileAppsData(int userId, int flags) {
19546        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19547        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19548            final String volumeUuid = vol.getFsUuid();
19549            synchronized (mInstallLock) {
19550                reconcileAppsDataLI(volumeUuid, userId, flags);
19551            }
19552        }
19553    }
19554
19555    /**
19556     * Reconcile all app data on given mounted volume.
19557     * <p>
19558     * Destroys app data that isn't expected, either due to uninstallation or
19559     * reinstallation on another volume.
19560     * <p>
19561     * Verifies that directories exist and that ownership and labeling is
19562     * correct for all installed apps.
19563     */
19564    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) {
19565        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
19566                + Integer.toHexString(flags));
19567
19568        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
19569        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
19570
19571        boolean restoreconNeeded = false;
19572
19573        // First look for stale data that doesn't belong, and check if things
19574        // have changed since we did our last restorecon
19575        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19576            if (StorageManager.isFileEncryptedNativeOrEmulated()
19577                    && !StorageManager.isUserKeyUnlocked(userId)) {
19578                throw new RuntimeException(
19579                        "Yikes, someone asked us to reconcile CE storage while " + userId
19580                                + " was still locked; this would have caused massive data loss!");
19581            }
19582
19583            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
19584
19585            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
19586            for (File file : files) {
19587                final String packageName = file.getName();
19588                try {
19589                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19590                } catch (PackageManagerException e) {
19591                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19592                    try {
19593                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19594                                StorageManager.FLAG_STORAGE_CE, 0);
19595                    } catch (InstallerException e2) {
19596                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19597                    }
19598                }
19599            }
19600        }
19601        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19602            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
19603
19604            final File[] files = FileUtils.listFilesOrEmpty(deDir);
19605            for (File file : files) {
19606                final String packageName = file.getName();
19607                try {
19608                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
19609                } catch (PackageManagerException e) {
19610                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
19611                    try {
19612                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
19613                                StorageManager.FLAG_STORAGE_DE, 0);
19614                    } catch (InstallerException e2) {
19615                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
19616                    }
19617                }
19618            }
19619        }
19620
19621        // Ensure that data directories are ready to roll for all packages
19622        // installed for this volume and user
19623        final List<PackageSetting> packages;
19624        synchronized (mPackages) {
19625            packages = mSettings.getVolumePackagesLPr(volumeUuid);
19626        }
19627        int preparedCount = 0;
19628        for (PackageSetting ps : packages) {
19629            final String packageName = ps.name;
19630            if (ps.pkg == null) {
19631                Slog.w(TAG, "Odd, missing scanned package " + packageName);
19632                // TODO: might be due to legacy ASEC apps; we should circle back
19633                // and reconcile again once they're scanned
19634                continue;
19635            }
19636
19637            if (ps.getInstalled(userId)) {
19638                prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19639
19640                if (maybeMigrateAppDataLIF(ps.pkg, userId)) {
19641                    // We may have just shuffled around app data directories, so
19642                    // prepare them one more time
19643                    prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded);
19644                }
19645
19646                preparedCount++;
19647            }
19648        }
19649
19650        if (restoreconNeeded) {
19651            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19652                SELinuxMMAC.setRestoreconDone(ceDir);
19653            }
19654            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
19655                SELinuxMMAC.setRestoreconDone(deDir);
19656            }
19657        }
19658
19659        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
19660                + " packages; restoreconNeeded was " + restoreconNeeded);
19661    }
19662
19663    /**
19664     * Prepare app data for the given app just after it was installed or
19665     * upgraded. This method carefully only touches users that it's installed
19666     * for, and it forces a restorecon to handle any seinfo changes.
19667     * <p>
19668     * Verifies that directories exist and that ownership and labeling is
19669     * correct for all installed apps. If there is an ownership mismatch, it
19670     * will try recovering system apps by wiping data; third-party app data is
19671     * left intact.
19672     * <p>
19673     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
19674     */
19675    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
19676        final PackageSetting ps;
19677        synchronized (mPackages) {
19678            ps = mSettings.mPackages.get(pkg.packageName);
19679            mSettings.writeKernelMappingLPr(ps);
19680        }
19681
19682        final UserManager um = mContext.getSystemService(UserManager.class);
19683        UserManagerInternal umInternal = getUserManagerInternal();
19684        for (UserInfo user : um.getUsers()) {
19685            final int flags;
19686            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
19687                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19688            } else if (umInternal.isUserRunning(user.id)) {
19689                flags = StorageManager.FLAG_STORAGE_DE;
19690            } else {
19691                continue;
19692            }
19693
19694            if (ps.getInstalled(user.id)) {
19695                // Whenever an app changes, force a restorecon of its data
19696                // TODO: when user data is locked, mark that we're still dirty
19697                prepareAppDataLIF(pkg, user.id, flags, true);
19698            }
19699        }
19700    }
19701
19702    /**
19703     * Prepare app data for the given app.
19704     * <p>
19705     * Verifies that directories exist and that ownership and labeling is
19706     * correct for all installed apps. If there is an ownership mismatch, this
19707     * will try recovering system apps by wiping data; third-party app data is
19708     * left intact.
19709     */
19710    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags,
19711            boolean restoreconNeeded) {
19712        if (pkg == null) {
19713            Slog.wtf(TAG, "Package was null!", new Throwable());
19714            return;
19715        }
19716        prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded);
19717        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19718        for (int i = 0; i < childCount; i++) {
19719            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded);
19720        }
19721    }
19722
19723    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags,
19724            boolean restoreconNeeded) {
19725        if (DEBUG_APP_DATA) {
19726            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
19727                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
19728        }
19729
19730        final String volumeUuid = pkg.volumeUuid;
19731        final String packageName = pkg.packageName;
19732        final ApplicationInfo app = pkg.applicationInfo;
19733        final int appId = UserHandle.getAppId(app.uid);
19734
19735        Preconditions.checkNotNull(app.seinfo);
19736
19737        try {
19738            mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19739                    appId, app.seinfo, app.targetSdkVersion);
19740        } catch (InstallerException e) {
19741            if (app.isSystemApp()) {
19742                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
19743                        + ", but trying to recover: " + e);
19744                destroyAppDataLeafLIF(pkg, userId, flags);
19745                try {
19746                    mInstaller.createAppData(volumeUuid, packageName, userId, flags,
19747                            appId, app.seinfo, app.targetSdkVersion);
19748                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
19749                } catch (InstallerException e2) {
19750                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
19751                }
19752            } else {
19753                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
19754            }
19755        }
19756
19757        if (restoreconNeeded) {
19758            try {
19759                mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId,
19760                        app.seinfo);
19761            } catch (InstallerException e) {
19762                Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
19763            }
19764        }
19765
19766        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19767            try {
19768                // CE storage is unlocked right now, so read out the inode and
19769                // remember for use later when it's locked
19770                // TODO: mark this structure as dirty so we persist it!
19771                final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId,
19772                        StorageManager.FLAG_STORAGE_CE);
19773                synchronized (mPackages) {
19774                    final PackageSetting ps = mSettings.mPackages.get(packageName);
19775                    if (ps != null) {
19776                        ps.setCeDataInode(ceDataInode, userId);
19777                    }
19778                }
19779            } catch (InstallerException e) {
19780                Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e);
19781            }
19782        }
19783
19784        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19785    }
19786
19787    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
19788        if (pkg == null) {
19789            Slog.wtf(TAG, "Package was null!", new Throwable());
19790            return;
19791        }
19792        prepareAppDataContentsLeafLIF(pkg, userId, flags);
19793        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
19794        for (int i = 0; i < childCount; i++) {
19795            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
19796        }
19797    }
19798
19799    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
19800        final String volumeUuid = pkg.volumeUuid;
19801        final String packageName = pkg.packageName;
19802        final ApplicationInfo app = pkg.applicationInfo;
19803
19804        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
19805            // Create a native library symlink only if we have native libraries
19806            // and if the native libraries are 32 bit libraries. We do not provide
19807            // this symlink for 64 bit libraries.
19808            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
19809                final String nativeLibPath = app.nativeLibraryDir;
19810                try {
19811                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
19812                            nativeLibPath, userId);
19813                } catch (InstallerException e) {
19814                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
19815                }
19816            }
19817        }
19818    }
19819
19820    /**
19821     * For system apps on non-FBE devices, this method migrates any existing
19822     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
19823     * requested by the app.
19824     */
19825    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
19826        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
19827                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
19828            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
19829                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
19830            try {
19831                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
19832                        storageTarget);
19833            } catch (InstallerException e) {
19834                logCriticalInfo(Log.WARN,
19835                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
19836            }
19837            return true;
19838        } else {
19839            return false;
19840        }
19841    }
19842
19843    public PackageFreezer freezePackage(String packageName, String killReason) {
19844        return new PackageFreezer(packageName, killReason);
19845    }
19846
19847    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
19848            String killReason) {
19849        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
19850            return new PackageFreezer();
19851        } else {
19852            return freezePackage(packageName, killReason);
19853        }
19854    }
19855
19856    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
19857            String killReason) {
19858        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
19859            return new PackageFreezer();
19860        } else {
19861            return freezePackage(packageName, killReason);
19862        }
19863    }
19864
19865    /**
19866     * Class that freezes and kills the given package upon creation, and
19867     * unfreezes it upon closing. This is typically used when doing surgery on
19868     * app code/data to prevent the app from running while you're working.
19869     */
19870    private class PackageFreezer implements AutoCloseable {
19871        private final String mPackageName;
19872        private final PackageFreezer[] mChildren;
19873
19874        private final boolean mWeFroze;
19875
19876        private final AtomicBoolean mClosed = new AtomicBoolean();
19877        private final CloseGuard mCloseGuard = CloseGuard.get();
19878
19879        /**
19880         * Create and return a stub freezer that doesn't actually do anything,
19881         * typically used when someone requested
19882         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
19883         * {@link PackageManager#DELETE_DONT_KILL_APP}.
19884         */
19885        public PackageFreezer() {
19886            mPackageName = null;
19887            mChildren = null;
19888            mWeFroze = false;
19889            mCloseGuard.open("close");
19890        }
19891
19892        public PackageFreezer(String packageName, String killReason) {
19893            synchronized (mPackages) {
19894                mPackageName = packageName;
19895                mWeFroze = mFrozenPackages.add(mPackageName);
19896
19897                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
19898                if (ps != null) {
19899                    killApplication(ps.name, ps.appId, killReason);
19900                }
19901
19902                final PackageParser.Package p = mPackages.get(packageName);
19903                if (p != null && p.childPackages != null) {
19904                    final int N = p.childPackages.size();
19905                    mChildren = new PackageFreezer[N];
19906                    for (int i = 0; i < N; i++) {
19907                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
19908                                killReason);
19909                    }
19910                } else {
19911                    mChildren = null;
19912                }
19913            }
19914            mCloseGuard.open("close");
19915        }
19916
19917        @Override
19918        protected void finalize() throws Throwable {
19919            try {
19920                mCloseGuard.warnIfOpen();
19921                close();
19922            } finally {
19923                super.finalize();
19924            }
19925        }
19926
19927        @Override
19928        public void close() {
19929            mCloseGuard.close();
19930            if (mClosed.compareAndSet(false, true)) {
19931                synchronized (mPackages) {
19932                    if (mWeFroze) {
19933                        mFrozenPackages.remove(mPackageName);
19934                    }
19935
19936                    if (mChildren != null) {
19937                        for (PackageFreezer freezer : mChildren) {
19938                            freezer.close();
19939                        }
19940                    }
19941                }
19942            }
19943        }
19944    }
19945
19946    /**
19947     * Verify that given package is currently frozen.
19948     */
19949    private void checkPackageFrozen(String packageName) {
19950        synchronized (mPackages) {
19951            if (!mFrozenPackages.contains(packageName)) {
19952                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
19953            }
19954        }
19955    }
19956
19957    @Override
19958    public int movePackage(final String packageName, final String volumeUuid) {
19959        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19960
19961        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
19962        final int moveId = mNextMoveId.getAndIncrement();
19963        mHandler.post(new Runnable() {
19964            @Override
19965            public void run() {
19966                try {
19967                    movePackageInternal(packageName, volumeUuid, moveId, user);
19968                } catch (PackageManagerException e) {
19969                    Slog.w(TAG, "Failed to move " + packageName, e);
19970                    mMoveCallbacks.notifyStatusChanged(moveId,
19971                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19972                }
19973            }
19974        });
19975        return moveId;
19976    }
19977
19978    private void movePackageInternal(final String packageName, final String volumeUuid,
19979            final int moveId, UserHandle user) throws PackageManagerException {
19980        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19981        final PackageManager pm = mContext.getPackageManager();
19982
19983        final boolean currentAsec;
19984        final String currentVolumeUuid;
19985        final File codeFile;
19986        final String installerPackageName;
19987        final String packageAbiOverride;
19988        final int appId;
19989        final String seinfo;
19990        final String label;
19991        final int targetSdkVersion;
19992        final PackageFreezer freezer;
19993        final int[] installedUserIds;
19994
19995        // reader
19996        synchronized (mPackages) {
19997            final PackageParser.Package pkg = mPackages.get(packageName);
19998            final PackageSetting ps = mSettings.mPackages.get(packageName);
19999            if (pkg == null || ps == null) {
20000                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
20001            }
20002
20003            if (pkg.applicationInfo.isSystemApp()) {
20004                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
20005                        "Cannot move system application");
20006            }
20007
20008            if (pkg.applicationInfo.isExternalAsec()) {
20009                currentAsec = true;
20010                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
20011            } else if (pkg.applicationInfo.isForwardLocked()) {
20012                currentAsec = true;
20013                currentVolumeUuid = "forward_locked";
20014            } else {
20015                currentAsec = false;
20016                currentVolumeUuid = ps.volumeUuid;
20017
20018                final File probe = new File(pkg.codePath);
20019                final File probeOat = new File(probe, "oat");
20020                if (!probe.isDirectory() || !probeOat.isDirectory()) {
20021                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20022                            "Move only supported for modern cluster style installs");
20023                }
20024            }
20025
20026            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
20027                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20028                        "Package already moved to " + volumeUuid);
20029            }
20030            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
20031                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
20032                        "Device admin cannot be moved");
20033            }
20034
20035            if (mFrozenPackages.contains(packageName)) {
20036                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
20037                        "Failed to move already frozen package");
20038            }
20039
20040            codeFile = new File(pkg.codePath);
20041            installerPackageName = ps.installerPackageName;
20042            packageAbiOverride = ps.cpuAbiOverrideString;
20043            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
20044            seinfo = pkg.applicationInfo.seinfo;
20045            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
20046            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
20047            freezer = new PackageFreezer(packageName, "movePackageInternal");
20048            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
20049        }
20050
20051        final Bundle extras = new Bundle();
20052        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
20053        extras.putString(Intent.EXTRA_TITLE, label);
20054        mMoveCallbacks.notifyCreated(moveId, extras);
20055
20056        int installFlags;
20057        final boolean moveCompleteApp;
20058        final File measurePath;
20059
20060        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
20061            installFlags = INSTALL_INTERNAL;
20062            moveCompleteApp = !currentAsec;
20063            measurePath = Environment.getDataAppDirectory(volumeUuid);
20064        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
20065            installFlags = INSTALL_EXTERNAL;
20066            moveCompleteApp = false;
20067            measurePath = storage.getPrimaryPhysicalVolume().getPath();
20068        } else {
20069            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
20070            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
20071                    || !volume.isMountedWritable()) {
20072                freezer.close();
20073                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20074                        "Move location not mounted private volume");
20075            }
20076
20077            Preconditions.checkState(!currentAsec);
20078
20079            installFlags = INSTALL_INTERNAL;
20080            moveCompleteApp = true;
20081            measurePath = Environment.getDataAppDirectory(volumeUuid);
20082        }
20083
20084        final PackageStats stats = new PackageStats(null, -1);
20085        synchronized (mInstaller) {
20086            for (int userId : installedUserIds) {
20087                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
20088                    freezer.close();
20089                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20090                            "Failed to measure package size");
20091                }
20092            }
20093        }
20094
20095        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
20096                + stats.dataSize);
20097
20098        final long startFreeBytes = measurePath.getFreeSpace();
20099        final long sizeBytes;
20100        if (moveCompleteApp) {
20101            sizeBytes = stats.codeSize + stats.dataSize;
20102        } else {
20103            sizeBytes = stats.codeSize;
20104        }
20105
20106        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
20107            freezer.close();
20108            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
20109                    "Not enough free space to move");
20110        }
20111
20112        mMoveCallbacks.notifyStatusChanged(moveId, 10);
20113
20114        final CountDownLatch installedLatch = new CountDownLatch(1);
20115        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
20116            @Override
20117            public void onUserActionRequired(Intent intent) throws RemoteException {
20118                throw new IllegalStateException();
20119            }
20120
20121            @Override
20122            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
20123                    Bundle extras) throws RemoteException {
20124                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
20125                        + PackageManager.installStatusToString(returnCode, msg));
20126
20127                installedLatch.countDown();
20128                freezer.close();
20129
20130                final int status = PackageManager.installStatusToPublicStatus(returnCode);
20131                switch (status) {
20132                    case PackageInstaller.STATUS_SUCCESS:
20133                        mMoveCallbacks.notifyStatusChanged(moveId,
20134                                PackageManager.MOVE_SUCCEEDED);
20135                        break;
20136                    case PackageInstaller.STATUS_FAILURE_STORAGE:
20137                        mMoveCallbacks.notifyStatusChanged(moveId,
20138                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
20139                        break;
20140                    default:
20141                        mMoveCallbacks.notifyStatusChanged(moveId,
20142                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
20143                        break;
20144                }
20145            }
20146        };
20147
20148        final MoveInfo move;
20149        if (moveCompleteApp) {
20150            // Kick off a thread to report progress estimates
20151            new Thread() {
20152                @Override
20153                public void run() {
20154                    while (true) {
20155                        try {
20156                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
20157                                break;
20158                            }
20159                        } catch (InterruptedException ignored) {
20160                        }
20161
20162                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
20163                        final int progress = 10 + (int) MathUtils.constrain(
20164                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
20165                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
20166                    }
20167                }
20168            }.start();
20169
20170            final String dataAppName = codeFile.getName();
20171            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
20172                    dataAppName, appId, seinfo, targetSdkVersion);
20173        } else {
20174            move = null;
20175        }
20176
20177        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
20178
20179        final Message msg = mHandler.obtainMessage(INIT_COPY);
20180        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
20181        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
20182                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
20183                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/);
20184        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
20185        msg.obj = params;
20186
20187        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
20188                System.identityHashCode(msg.obj));
20189        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
20190                System.identityHashCode(msg.obj));
20191
20192        mHandler.sendMessage(msg);
20193    }
20194
20195    @Override
20196    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
20197        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
20198
20199        final int realMoveId = mNextMoveId.getAndIncrement();
20200        final Bundle extras = new Bundle();
20201        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
20202        mMoveCallbacks.notifyCreated(realMoveId, extras);
20203
20204        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
20205            @Override
20206            public void onCreated(int moveId, Bundle extras) {
20207                // Ignored
20208            }
20209
20210            @Override
20211            public void onStatusChanged(int moveId, int status, long estMillis) {
20212                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
20213            }
20214        };
20215
20216        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20217        storage.setPrimaryStorageUuid(volumeUuid, callback);
20218        return realMoveId;
20219    }
20220
20221    @Override
20222    public int getMoveStatus(int moveId) {
20223        mContext.enforceCallingOrSelfPermission(
20224                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20225        return mMoveCallbacks.mLastStatus.get(moveId);
20226    }
20227
20228    @Override
20229    public void registerMoveCallback(IPackageMoveObserver callback) {
20230        mContext.enforceCallingOrSelfPermission(
20231                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20232        mMoveCallbacks.register(callback);
20233    }
20234
20235    @Override
20236    public void unregisterMoveCallback(IPackageMoveObserver callback) {
20237        mContext.enforceCallingOrSelfPermission(
20238                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
20239        mMoveCallbacks.unregister(callback);
20240    }
20241
20242    @Override
20243    public boolean setInstallLocation(int loc) {
20244        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
20245                null);
20246        if (getInstallLocation() == loc) {
20247            return true;
20248        }
20249        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
20250                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
20251            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
20252                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
20253            return true;
20254        }
20255        return false;
20256   }
20257
20258    @Override
20259    public int getInstallLocation() {
20260        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
20261                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
20262                PackageHelper.APP_INSTALL_AUTO);
20263    }
20264
20265    /** Called by UserManagerService */
20266    void cleanUpUser(UserManagerService userManager, int userHandle) {
20267        synchronized (mPackages) {
20268            mDirtyUsers.remove(userHandle);
20269            mUserNeedsBadging.delete(userHandle);
20270            mSettings.removeUserLPw(userHandle);
20271            mPendingBroadcasts.remove(userHandle);
20272            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
20273            removeUnusedPackagesLPw(userManager, userHandle);
20274        }
20275    }
20276
20277    /**
20278     * We're removing userHandle and would like to remove any downloaded packages
20279     * that are no longer in use by any other user.
20280     * @param userHandle the user being removed
20281     */
20282    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
20283        final boolean DEBUG_CLEAN_APKS = false;
20284        int [] users = userManager.getUserIds();
20285        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
20286        while (psit.hasNext()) {
20287            PackageSetting ps = psit.next();
20288            if (ps.pkg == null) {
20289                continue;
20290            }
20291            final String packageName = ps.pkg.packageName;
20292            // Skip over if system app
20293            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
20294                continue;
20295            }
20296            if (DEBUG_CLEAN_APKS) {
20297                Slog.i(TAG, "Checking package " + packageName);
20298            }
20299            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
20300            if (keep) {
20301                if (DEBUG_CLEAN_APKS) {
20302                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
20303                }
20304            } else {
20305                for (int i = 0; i < users.length; i++) {
20306                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
20307                        keep = true;
20308                        if (DEBUG_CLEAN_APKS) {
20309                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
20310                                    + users[i]);
20311                        }
20312                        break;
20313                    }
20314                }
20315            }
20316            if (!keep) {
20317                if (DEBUG_CLEAN_APKS) {
20318                    Slog.i(TAG, "  Removing package " + packageName);
20319                }
20320                mHandler.post(new Runnable() {
20321                    public void run() {
20322                        deletePackageX(packageName, userHandle, 0);
20323                    } //end run
20324                });
20325            }
20326        }
20327    }
20328
20329    /** Called by UserManagerService */
20330    void createNewUser(int userId) {
20331        synchronized (mInstallLock) {
20332            mSettings.createNewUserLI(this, mInstaller, userId);
20333        }
20334        synchronized (mPackages) {
20335            scheduleWritePackageRestrictionsLocked(userId);
20336            scheduleWritePackageListLocked(userId);
20337            applyFactoryDefaultBrowserLPw(userId);
20338            primeDomainVerificationsLPw(userId);
20339        }
20340    }
20341
20342    void onBeforeUserStartUninitialized(final int userId) {
20343        synchronized (mPackages) {
20344            if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20345                return;
20346            }
20347        }
20348        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20349        // If permission review for legacy apps is required, we represent
20350        // dagerous permissions for such apps as always granted runtime
20351        // permissions to keep per user flag state whether review is needed.
20352        // Hence, if a new user is added we have to propagate dangerous
20353        // permission grants for these legacy apps.
20354        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
20355            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
20356                    | UPDATE_PERMISSIONS_REPLACE_ALL);
20357        }
20358    }
20359
20360    @Override
20361    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
20362        mContext.enforceCallingOrSelfPermission(
20363                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
20364                "Only package verification agents can read the verifier device identity");
20365
20366        synchronized (mPackages) {
20367            return mSettings.getVerifierDeviceIdentityLPw();
20368        }
20369    }
20370
20371    @Override
20372    public void setPermissionEnforced(String permission, boolean enforced) {
20373        // TODO: Now that we no longer change GID for storage, this should to away.
20374        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
20375                "setPermissionEnforced");
20376        if (READ_EXTERNAL_STORAGE.equals(permission)) {
20377            synchronized (mPackages) {
20378                if (mSettings.mReadExternalStorageEnforced == null
20379                        || mSettings.mReadExternalStorageEnforced != enforced) {
20380                    mSettings.mReadExternalStorageEnforced = enforced;
20381                    mSettings.writeLPr();
20382                }
20383            }
20384            // kill any non-foreground processes so we restart them and
20385            // grant/revoke the GID.
20386            final IActivityManager am = ActivityManagerNative.getDefault();
20387            if (am != null) {
20388                final long token = Binder.clearCallingIdentity();
20389                try {
20390                    am.killProcessesBelowForeground("setPermissionEnforcement");
20391                } catch (RemoteException e) {
20392                } finally {
20393                    Binder.restoreCallingIdentity(token);
20394                }
20395            }
20396        } else {
20397            throw new IllegalArgumentException("No selective enforcement for " + permission);
20398        }
20399    }
20400
20401    @Override
20402    @Deprecated
20403    public boolean isPermissionEnforced(String permission) {
20404        return true;
20405    }
20406
20407    @Override
20408    public boolean isStorageLow() {
20409        final long token = Binder.clearCallingIdentity();
20410        try {
20411            final DeviceStorageMonitorInternal
20412                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
20413            if (dsm != null) {
20414                return dsm.isMemoryLow();
20415            } else {
20416                return false;
20417            }
20418        } finally {
20419            Binder.restoreCallingIdentity(token);
20420        }
20421    }
20422
20423    @Override
20424    public IPackageInstaller getPackageInstaller() {
20425        return mInstallerService;
20426    }
20427
20428    private boolean userNeedsBadging(int userId) {
20429        int index = mUserNeedsBadging.indexOfKey(userId);
20430        if (index < 0) {
20431            final UserInfo userInfo;
20432            final long token = Binder.clearCallingIdentity();
20433            try {
20434                userInfo = sUserManager.getUserInfo(userId);
20435            } finally {
20436                Binder.restoreCallingIdentity(token);
20437            }
20438            final boolean b;
20439            if (userInfo != null && userInfo.isManagedProfile()) {
20440                b = true;
20441            } else {
20442                b = false;
20443            }
20444            mUserNeedsBadging.put(userId, b);
20445            return b;
20446        }
20447        return mUserNeedsBadging.valueAt(index);
20448    }
20449
20450    @Override
20451    public KeySet getKeySetByAlias(String packageName, String alias) {
20452        if (packageName == null || alias == null) {
20453            return null;
20454        }
20455        synchronized(mPackages) {
20456            final PackageParser.Package pkg = mPackages.get(packageName);
20457            if (pkg == null) {
20458                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20459                throw new IllegalArgumentException("Unknown package: " + packageName);
20460            }
20461            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20462            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
20463        }
20464    }
20465
20466    @Override
20467    public KeySet getSigningKeySet(String packageName) {
20468        if (packageName == null) {
20469            return null;
20470        }
20471        synchronized(mPackages) {
20472            final PackageParser.Package pkg = mPackages.get(packageName);
20473            if (pkg == null) {
20474                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20475                throw new IllegalArgumentException("Unknown package: " + packageName);
20476            }
20477            if (pkg.applicationInfo.uid != Binder.getCallingUid()
20478                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
20479                throw new SecurityException("May not access signing KeySet of other apps.");
20480            }
20481            KeySetManagerService ksms = mSettings.mKeySetManagerService;
20482            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
20483        }
20484    }
20485
20486    @Override
20487    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
20488        if (packageName == null || ks == null) {
20489            return false;
20490        }
20491        synchronized(mPackages) {
20492            final PackageParser.Package pkg = mPackages.get(packageName);
20493            if (pkg == null) {
20494                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20495                throw new IllegalArgumentException("Unknown package: " + packageName);
20496            }
20497            IBinder ksh = ks.getToken();
20498            if (ksh instanceof KeySetHandle) {
20499                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20500                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
20501            }
20502            return false;
20503        }
20504    }
20505
20506    @Override
20507    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
20508        if (packageName == null || ks == null) {
20509            return false;
20510        }
20511        synchronized(mPackages) {
20512            final PackageParser.Package pkg = mPackages.get(packageName);
20513            if (pkg == null) {
20514                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
20515                throw new IllegalArgumentException("Unknown package: " + packageName);
20516            }
20517            IBinder ksh = ks.getToken();
20518            if (ksh instanceof KeySetHandle) {
20519                KeySetManagerService ksms = mSettings.mKeySetManagerService;
20520                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
20521            }
20522            return false;
20523        }
20524    }
20525
20526    private void deletePackageIfUnusedLPr(final String packageName) {
20527        PackageSetting ps = mSettings.mPackages.get(packageName);
20528        if (ps == null) {
20529            return;
20530        }
20531        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
20532            // TODO Implement atomic delete if package is unused
20533            // It is currently possible that the package will be deleted even if it is installed
20534            // after this method returns.
20535            mHandler.post(new Runnable() {
20536                public void run() {
20537                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
20538                }
20539            });
20540        }
20541    }
20542
20543    /**
20544     * Check and throw if the given before/after packages would be considered a
20545     * downgrade.
20546     */
20547    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
20548            throws PackageManagerException {
20549        if (after.versionCode < before.mVersionCode) {
20550            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20551                    "Update version code " + after.versionCode + " is older than current "
20552                    + before.mVersionCode);
20553        } else if (after.versionCode == before.mVersionCode) {
20554            if (after.baseRevisionCode < before.baseRevisionCode) {
20555                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20556                        "Update base revision code " + after.baseRevisionCode
20557                        + " is older than current " + before.baseRevisionCode);
20558            }
20559
20560            if (!ArrayUtils.isEmpty(after.splitNames)) {
20561                for (int i = 0; i < after.splitNames.length; i++) {
20562                    final String splitName = after.splitNames[i];
20563                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
20564                    if (j != -1) {
20565                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
20566                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
20567                                    "Update split " + splitName + " revision code "
20568                                    + after.splitRevisionCodes[i] + " is older than current "
20569                                    + before.splitRevisionCodes[j]);
20570                        }
20571                    }
20572                }
20573            }
20574        }
20575    }
20576
20577    private static class MoveCallbacks extends Handler {
20578        private static final int MSG_CREATED = 1;
20579        private static final int MSG_STATUS_CHANGED = 2;
20580
20581        private final RemoteCallbackList<IPackageMoveObserver>
20582                mCallbacks = new RemoteCallbackList<>();
20583
20584        private final SparseIntArray mLastStatus = new SparseIntArray();
20585
20586        public MoveCallbacks(Looper looper) {
20587            super(looper);
20588        }
20589
20590        public void register(IPackageMoveObserver callback) {
20591            mCallbacks.register(callback);
20592        }
20593
20594        public void unregister(IPackageMoveObserver callback) {
20595            mCallbacks.unregister(callback);
20596        }
20597
20598        @Override
20599        public void handleMessage(Message msg) {
20600            final SomeArgs args = (SomeArgs) msg.obj;
20601            final int n = mCallbacks.beginBroadcast();
20602            for (int i = 0; i < n; i++) {
20603                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
20604                try {
20605                    invokeCallback(callback, msg.what, args);
20606                } catch (RemoteException ignored) {
20607                }
20608            }
20609            mCallbacks.finishBroadcast();
20610            args.recycle();
20611        }
20612
20613        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
20614                throws RemoteException {
20615            switch (what) {
20616                case MSG_CREATED: {
20617                    callback.onCreated(args.argi1, (Bundle) args.arg2);
20618                    break;
20619                }
20620                case MSG_STATUS_CHANGED: {
20621                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
20622                    break;
20623                }
20624            }
20625        }
20626
20627        private void notifyCreated(int moveId, Bundle extras) {
20628            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
20629
20630            final SomeArgs args = SomeArgs.obtain();
20631            args.argi1 = moveId;
20632            args.arg2 = extras;
20633            obtainMessage(MSG_CREATED, args).sendToTarget();
20634        }
20635
20636        private void notifyStatusChanged(int moveId, int status) {
20637            notifyStatusChanged(moveId, status, -1);
20638        }
20639
20640        private void notifyStatusChanged(int moveId, int status, long estMillis) {
20641            Slog.v(TAG, "Move " + moveId + " status " + status);
20642
20643            final SomeArgs args = SomeArgs.obtain();
20644            args.argi1 = moveId;
20645            args.argi2 = status;
20646            args.arg3 = estMillis;
20647            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
20648
20649            synchronized (mLastStatus) {
20650                mLastStatus.put(moveId, status);
20651            }
20652        }
20653    }
20654
20655    private final static class OnPermissionChangeListeners extends Handler {
20656        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
20657
20658        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
20659                new RemoteCallbackList<>();
20660
20661        public OnPermissionChangeListeners(Looper looper) {
20662            super(looper);
20663        }
20664
20665        @Override
20666        public void handleMessage(Message msg) {
20667            switch (msg.what) {
20668                case MSG_ON_PERMISSIONS_CHANGED: {
20669                    final int uid = msg.arg1;
20670                    handleOnPermissionsChanged(uid);
20671                } break;
20672            }
20673        }
20674
20675        public void addListenerLocked(IOnPermissionsChangeListener listener) {
20676            mPermissionListeners.register(listener);
20677
20678        }
20679
20680        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
20681            mPermissionListeners.unregister(listener);
20682        }
20683
20684        public void onPermissionsChanged(int uid) {
20685            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
20686                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
20687            }
20688        }
20689
20690        private void handleOnPermissionsChanged(int uid) {
20691            final int count = mPermissionListeners.beginBroadcast();
20692            try {
20693                for (int i = 0; i < count; i++) {
20694                    IOnPermissionsChangeListener callback = mPermissionListeners
20695                            .getBroadcastItem(i);
20696                    try {
20697                        callback.onPermissionsChanged(uid);
20698                    } catch (RemoteException e) {
20699                        Log.e(TAG, "Permission listener is dead", e);
20700                    }
20701                }
20702            } finally {
20703                mPermissionListeners.finishBroadcast();
20704            }
20705        }
20706    }
20707
20708    private class PackageManagerInternalImpl extends PackageManagerInternal {
20709        @Override
20710        public void setLocationPackagesProvider(PackagesProvider provider) {
20711            synchronized (mPackages) {
20712                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
20713            }
20714        }
20715
20716        @Override
20717        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
20718            synchronized (mPackages) {
20719                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
20720            }
20721        }
20722
20723        @Override
20724        public void setSmsAppPackagesProvider(PackagesProvider provider) {
20725            synchronized (mPackages) {
20726                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
20727            }
20728        }
20729
20730        @Override
20731        public void setDialerAppPackagesProvider(PackagesProvider provider) {
20732            synchronized (mPackages) {
20733                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
20734            }
20735        }
20736
20737        @Override
20738        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
20739            synchronized (mPackages) {
20740                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
20741            }
20742        }
20743
20744        @Override
20745        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
20746            synchronized (mPackages) {
20747                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
20748            }
20749        }
20750
20751        @Override
20752        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
20753            synchronized (mPackages) {
20754                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
20755                        packageName, userId);
20756            }
20757        }
20758
20759        @Override
20760        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
20761            synchronized (mPackages) {
20762                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
20763                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
20764                        packageName, userId);
20765            }
20766        }
20767
20768        @Override
20769        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
20770            synchronized (mPackages) {
20771                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
20772                        packageName, userId);
20773            }
20774        }
20775
20776        @Override
20777        public void setKeepUninstalledPackages(final List<String> packageList) {
20778            Preconditions.checkNotNull(packageList);
20779            List<String> removedFromList = null;
20780            synchronized (mPackages) {
20781                if (mKeepUninstalledPackages != null) {
20782                    final int packagesCount = mKeepUninstalledPackages.size();
20783                    for (int i = 0; i < packagesCount; i++) {
20784                        String oldPackage = mKeepUninstalledPackages.get(i);
20785                        if (packageList != null && packageList.contains(oldPackage)) {
20786                            continue;
20787                        }
20788                        if (removedFromList == null) {
20789                            removedFromList = new ArrayList<>();
20790                        }
20791                        removedFromList.add(oldPackage);
20792                    }
20793                }
20794                mKeepUninstalledPackages = new ArrayList<>(packageList);
20795                if (removedFromList != null) {
20796                    final int removedCount = removedFromList.size();
20797                    for (int i = 0; i < removedCount; i++) {
20798                        deletePackageIfUnusedLPr(removedFromList.get(i));
20799                    }
20800                }
20801            }
20802        }
20803
20804        @Override
20805        public boolean isPermissionsReviewRequired(String packageName, int userId) {
20806            synchronized (mPackages) {
20807                // If we do not support permission review, done.
20808                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
20809                    return false;
20810                }
20811
20812                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
20813                if (packageSetting == null) {
20814                    return false;
20815                }
20816
20817                // Permission review applies only to apps not supporting the new permission model.
20818                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
20819                    return false;
20820                }
20821
20822                // Legacy apps have the permission and get user consent on launch.
20823                PermissionsState permissionsState = packageSetting.getPermissionsState();
20824                return permissionsState.isPermissionReviewRequired(userId);
20825            }
20826        }
20827
20828        @Override
20829        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
20830            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
20831        }
20832
20833        @Override
20834        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20835                int userId) {
20836            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
20837        }
20838
20839        @Override
20840        public void setDeviceAndProfileOwnerPackages(
20841                int deviceOwnerUserId, String deviceOwnerPackage,
20842                SparseArray<String> profileOwnerPackages) {
20843            mProtectedPackages.setDeviceAndProfileOwnerPackages(
20844                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
20845        }
20846
20847        @Override
20848        public boolean canPackageBeWiped(int userId, String packageName) {
20849            return mProtectedPackages.canPackageBeWiped(userId,
20850                    packageName);
20851        }
20852    }
20853
20854    @Override
20855    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
20856        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
20857        synchronized (mPackages) {
20858            final long identity = Binder.clearCallingIdentity();
20859            try {
20860                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
20861                        packageNames, userId);
20862            } finally {
20863                Binder.restoreCallingIdentity(identity);
20864            }
20865        }
20866    }
20867
20868    private static void enforceSystemOrPhoneCaller(String tag) {
20869        int callingUid = Binder.getCallingUid();
20870        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
20871            throw new SecurityException(
20872                    "Cannot call " + tag + " from UID " + callingUid);
20873        }
20874    }
20875
20876    boolean isHistoricalPackageUsageAvailable() {
20877        return mPackageUsage.isHistoricalPackageUsageAvailable();
20878    }
20879
20880    /**
20881     * Return a <b>copy</b> of the collection of packages known to the package manager.
20882     * @return A copy of the values of mPackages.
20883     */
20884    Collection<PackageParser.Package> getPackages() {
20885        synchronized (mPackages) {
20886            return new ArrayList<>(mPackages.values());
20887        }
20888    }
20889
20890    /**
20891     * Logs process start information (including base APK hash) to the security log.
20892     * @hide
20893     */
20894    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
20895            String apkFile, int pid) {
20896        if (!SecurityLog.isLoggingEnabled()) {
20897            return;
20898        }
20899        Bundle data = new Bundle();
20900        data.putLong("startTimestamp", System.currentTimeMillis());
20901        data.putString("processName", processName);
20902        data.putInt("uid", uid);
20903        data.putString("seinfo", seinfo);
20904        data.putString("apkFile", apkFile);
20905        data.putInt("pid", pid);
20906        Message msg = mProcessLoggingHandler.obtainMessage(
20907                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
20908        msg.setData(data);
20909        mProcessLoggingHandler.sendMessage(msg);
20910    }
20911}
20912